With the old Ziko python use while to loop _python

Source: Internet
Author: User
Tags time interval in python

In Python, it also has this meaning, but a bit of a difference is, "when ... Time "This condition is established within a range or time interval so that Python can do a lot of things during this time interval. It's like a situation like this:

While age is greater than 60 years:--------> When older than 60 years old
Retirement--------> Actions to be performed in accordance with the above conditions
Imagine, if you make a door, this door is to use the above conditions to regulate the switch, suppose a lot of people go through this and age, and as long as they're older than 60, they retire (doors open, people can go out), one after another, and suddenly a man is 50, then this cycle stops here, That's when he doesn't meet the conditions.

This is the while loop. To write a more serious process, you can look at the following figure:

Guess the number game again.

This tutorial has a talk, is to do a little game with reader, in which to do a guessing game, at that time encountered a problem, is only guessed one or two times, if not guessed, the program can not continue to run.

Not long ago, there is a college student friend (his name Hangyuan Li), send me an email, let me see his game, can realize many guesses, until guessed. This is a student who likes to study.

I am here to write his procedures Christine recorded here, the unit Hangyuan Li students do not take offense, if Hangyuan Li students think this violation of their own intellectual property, you can tell me, I immediately removed this code.

Copy Code code as follows:

#! /usr/bin/env python
#coding: UTF-8

Import Random

I=0
While I < 4:
print ' ******************************** '
num = input (' Please enter any number from 0 to 9: ') #李同学用的是python3

Xnum = Random.randint (0,9)

x = 3-i

if num = = Xnum:
print ' It's good luck, you guessed it! '
Break
Elif num > Xnum:
print ' You guess big!\n haha, the correct answer is:%s\n You also have the chance of%s! "%" (xnum,x)
Elif Num < xnum:
print ' You guess small!\n haha, the correct answer is:%s\n You also have the chance of%s! "%" (xnum,x)
print ' ******************************** '

i + 1

We'll use this procedure to analyze, first look while i<4, this is the program in order to guess limit the number of times, the maximum is three times, please reader note, in the while loop body in the last sentence: I +=1, this is said that each cycle to the end, I added 1, when bool (i<4) = False, the cycle is no longer.

when bool (I<4) =true, executes the statement in the loop body. In the loop, let the user input an integer, and then the program randomly select an integer, and finally determine whether the number of randomly generated and user input is equal, and use the IF statement to judge three different situations.

According to the code above, reader see if you can modify it?

To make the user's experience more satisfying, you might want to expand the range of integers you've entered, between 1 and 100.

Copy Code code as follows:

Num_input = raw_input ("Please input one integer this is in 1:") #我用的是python2.7, distinguished from Li in the input instructions

The program receives the input with the num_input variable. However, please reader must pay attention to, see here want to sleep to play the spirit, I want to share a multi-year programming experience, please keep in mind: Any user input content is unreliable. It means a lot, but there's not much to explain here, and you need to experience it later in your programming career. To do this, we want to verify that the user input to meet our requirements, we ask the user input is 1 to 100 of integers, then do the following test:

Whether the input is an integer
If it's an integer, whether it's between 1 and 100.
To do this, do:

Copy Code code as follows:

If not Num_input.isdigit (): #str. IsDigit () is used to determine whether a string is purely composed of numbers
Print "Please input interger."
elif Int (num_input) <0 and int (num_input) >=100:
Print "The number should is in 1 to 100."
Else
Pass #这里用pass, which means to temporarily omit, if the previous requirements are met, the statement should be executed here

Then look at the program Hangyuan Li classmate, in the circulation of a random number, so that users each input, face is a new random number. Such a guessing number game is too difficult. I hope that the program produces a number until guess, and that's the number. So, you have to move the command to generate random numbers before the loop.

Copy Code code as follows:

Import Random

Number = Random.randint (1,100)

While True: #不限制用户的次数了
...

Observe the program of Lee's classmate, one thing that needs to be shown to all of you is that in a conditional expression, it's best to have the same type of data on either side, and the above program has the following: the Num>xnum-style conditional expression, while one side is the data of the type int generated by the program and the STR type data obtained by the input In some cases can run, why? Reader can you understand? When it's all numbers, it's OK. But this is not good.

So, in this way, rewrite this guess-number program:

Copy Code code as follows:

#!/usr/bin/env python
#coding: Utf-8

Import Random

Number = Random.randint (1,100)

Guess = 0

While True:

Num_input = raw_input ("Please input one integer this is in 1 to 100:")
Guess +=1

If not Num_input.isdigit ():
Print "Please input interger."
elif Int (num_input) <0 and int (num_input) >=100:
Print "The number should is in 1 to 100."
Else
If Number==int (num_input):
Print "OK, you are good. It is only%d and then you successed. " %guess
Break
Elif Number>int (num_input):
Print "Your number is more less."
Elif Number<int (num_input):
Print "Your number is bigger."
Else
Print "There is something bad, I'll not work"

For reference, reader can also be improved.

Break and Continue

The break, which has been shown in the example above, is meant to interrupt the loop in this place and jump out of the loop body. The following brief example is more obvious:

Copy Code code as follows:

#!/usr/bin/env python
#coding: Utf-8

A = 8
While a:
If a%2==0:
Break
Else
print '%d is odd number '%a
A = 0
print '%d is even number '%a

When A=8, execute the break in the loop body, jump out of the fantasy, execute the final print statement, get the result:

Copy Code code as follows:

8 is even number

If a=9, execute the print in else, then a=0, the loop executes once, then the break, and the result:

Copy Code code as follows:

9 is odd number
0 is even number

And continue is to jump from the current position (that is, the location of the continue) to the back of the last line of the loop body (not to execute the last line), in terms of a loop body, just like the end of the last line, where is the back? Of course it's the beginning.

Copy Code code as follows:

#!/usr/bin/env python
#coding: Utf-8

A = 9
While a:
If a%2==0:
A-=1
Continue #如果是偶数, return to the beginning of the loop
Else
print '%d is odd number '%a #如果是奇数, printed
A-=1

In fact, for these two things, I personally in the programming is rarely used. I have a stubborn idea, try to put the conditions before the cycle to do enough, do not jump in the loop, not only the readability of the decline, sometimes they are confused.

Copy Code code as follows:

While...else

The combination of these two is somewhat similar to if ... else, only one example is required to understand, of course, when you encounter else, it means that you are not in the while loop.

Copy Code code as follows:

#!/usr/bin/env python

Count = 0
While Count < 5:
Print count, "is less than 5"
Count = Count + 1
Else
Print count, "is not less than 5"

Execution results:

Copy Code code as follows:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.