I want to keep up with Python, use while for loop, and learn python

Source: Internet
Author: User

I want to keep up with Python, use while for loop, and learn python

In python, it also has this meaning, but the difference is that "when... "This condition is set up within a certain range or interval, so that python can do many things during this interval. It is like this scenario:

While age over 60: --------> when age over 60
Retirement --------> any action that meets the above conditions
Imagine that if a door is created, the above conditions are used to regulate the switch. Assume that many people pass through the door and report their ages as long as they are older than 60, just retire (when the door opens, people can go out). One cycle goes down one by one, and suddenly a person is 50 years old, then the cycle stops here, that is, at this time he does not meet the conditions.

This is the while loop. To write a serious process, you can see:

Play a digital game again

In this tutorial, I made a quiz game with the viewer. I encountered a problem that I could only guess twice. If I couldn't guess it, the program cannot continue running.

Not long ago, a college student friend (his name is Li Hang) sent me an email asking me to watch his game, so that he could guess the number multiple times until he guessed it. This is a college student who really enjoys learning.

Here I will write a program written by Li Hang. I don't want to be surprised at the unit. If Li Hang thinks this constitutes a violation of his intellectual property rights, I can tell you that I will immediately remove this code.

Copy codeThe Code is as follows:
#! /Usr/bin/env python
# Coding: UTF-8

Import random

I = 0
While I <4:
Print '********************************'
Num = input ('enter any number from 0 to 9: ') # Use python3.

Xnum = random. randint (0, 9)

X = 3-I

If num = xnum:
Print 'lucky! You guessed it! '
Break
Elif num> xnum:
Print ''' you guessed it! \ N Haha, correct answer: % s \ n you have % s chance! ''' % (Xnum, x)
Elif num <xnum:
Print! \ N Haha, correct answer: % s \ n you have % s chance! ''' % (Xnum, x)
Print '********************************'

I + = 1

We will use this program for analysis. First, let's look at the while I <4. This is the maximum number of guesses in the program, which is three times, the last sentence in the while LOOP body: I + = 1, which means that 1 is added to I after each loop ends. When bool (I <4) = False, it is no longer a loop.

When bool (I <4) = True, the statement in the loop body is executed. In the loop body, let the user enter an integer, then the program selects an integer randomly, and finally determines whether the number generated randomly is equal to the number entered by the user, and uses the if statement to determine three different situations.

Based on the above Code, check whether the code can be modified?

To improve the user experience, you can extend the input integer range between 1 and 100.

Copy codeThe Code is as follows:
Num_input = raw_input ("please input one integer that is in 1 to 100:") # I use python2.7, which is different from Li in the input command.

The program uses the num_input variable to receive the input content. However, you must be aware of the importance of putting a column on the official website. If you want to go to bed here, you need to share your many years of programming experience. Remember that the content entered by any user is unreliable. This sentence has a profound meaning, but I will not explain it too much here. You need to experience it in your subsequent programming career. Therefore, we need to check whether the user input meets our requirements. If the user input is an integer between 1 and 100, we need to perform the following test:

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

Copy codeThe Code is as follows:
If not num_input.isdigit (): # str. isdigit () is used to determine whether a string is composed of digits.
Print "Please input interger ."
Elif int (num_input) <0 and int (num_input) >=100:
Print "The number shoshould be in 1 to 100 ."
Else:
Pass # Here we use pass, which means temporarily omitted. If the preceding requirements are met, we should execute the statement here.

Let's look at the program of Li Hang and generate a random number in the loop, so that each time the user inputs a new random number. It is too difficult to guess such a digital game. I want the program to generate a number until it is guessed. Therefore, we need to move the random numbers generated before the loop.

Copy codeThe Code is as follows:
Import random

Number = random. randint (1,100)

While True: # no limit on the number of users
...

To observe the program of Li, another point that needs to be explicit to the column is that in the conditional expression, the two sides should preferably be the same type of data. The above program has the following conditional expressions: num> xnum style, one side is the int type data generated by the program, and the other side is the str type data obtained by the input function. It can be run in some cases. Why? Can an official understand it? It can be a number. However, this is not good.

In this way, rewrite this guess number program:

Copy codeThe Code is 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 that 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 shoshould be in 1 to 100 ."
Else:
If number = int (num_input ):
Print "OK, you are good. It is only % d, 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 will not work"

The above is for reference and can be improved.

Break and continue

Break, which has already appeared in the above example, means to interrupt the loop in this place and jump out of the loop body. The following simple example is more obvious:

Copy codeThe Code is as follows:
#! /Usr/bin/env python
# Coding: UTF-8

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

When a = 8, run the break in the loop body, jump out of the fantasy, and execute the final print statement. The result is as follows:

Copy codeThe Code is as follows:
8 is even number

If a = 9, execute the print in else, then a = 0, the loop is executed once, and then break. The result is as follows:

Copy codeThe Code is as follows:
9 is odd number
0 is even number

The continue is to jump from the current position (that is, the position of the continue) to the end of the last row of the loop body (not to execute the last row). For a loop body, just like connecting the beginning and end, where is the end of the last line? Of course.

Copy codeThe Code is as follows:
#! /Usr/bin/env python
# Coding: UTF-8

A = 9
While:
If a % 2 = 0:
A-= 1
Continue # if it is an even number, the start of the loop is returned.
Else:
Print "% d is odd number" % a # print it out if it is an odd number
A-= 1

In fact, I personally seldom use these two things in programming. I have a stubborn idea that I should try my best to make the conditions adequate before the loop. Don't skip in the loop, not only will the readability decrease, but sometimes I will be confused.

Copy codeThe Code is as follows:
While... else

The cooperation between the two is a bit similar to if... else. You only need an example column to understand it. Of course, when you encounter else, it means that it is no longer in the while loop.

Copy codeThe Code is 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 result:

Copy codeThe Code is 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




Related Article

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.