Python process control instance code

  • 2020-04-02 09:32:36
  • OfStack

First, introduce the if-else conditional statement. The if statement is used to selectively execute a particular block of code based on the true or false of the expression, controlling the flow of the program. The usage is the same as Java and other languages. There's an elif shorthand for else if.
Such as:
 
if x > 3: 
print("greater") 
elif x == 3: 
print("eq") 
else: 
print("small") 

Let's move on to the while statement. The while statement is used to execute a particular block repeatedly when the conditional expression is true.
First look at a sample program, and then give a description:
 
x = int(input("enter a integer:")) 
while x != -1: 
print(x) 
x = int(input("next number:")) 
else: 
print("end") 
print('over') 

In this code, as long as the value of x is not equal to negative 1, it will be repeated. What's special about c/c++/ Java is the else statement. Here, else is an optional statement. When the conditional expression is false, out of the while loop, the block under the else statement is executed.
Finally, look at the for loop. The for... In is another looping statement in Python. The main purpose is to iterate over the sequence of objects. Usage:
 
for x in range(1,5): 
print(x) 
print('over') 

For looping statements, you need a way out of the current loop and out of the loop. In Python, you use the continue and break statements. The use of these two syntaxes is the same as that of c/c++/ Java, so I won't repeat it again.
With these three methods, you can do all the flow control in Python!

Related articles: