Python faithfully executes them in their order.
What if you want to change the execution order of the statement flow?
As you might have guessed, this is achieved through control flow statements.
There are three kinds of control flow statements in Python - if, for and while.
if statement
The if statement is used to test a condition, if the condition is true (True) , we run a block of statements (called an if-block)
Otherwise we process another block of statements (called else-block). The else clause is optional.
age = 20
if age >18:
print("成年人")
else :
print("未成年")
# "未成年"
In the program, we judge whether the value of age is greater than 18, if it is greater than output "adult", otherwise output "minor"
Notice:
18 is followed by a colon
print("Adult") is indented by 4 spaces before it is called an if-block
You can easily understand the execution process of the conditional statement through the following figure:
Use multiple if
In this program, we get the guessed number from the user, and then check if the number is the one we have. We set the variable number to whatever integer we want, in this case 28. Then, we use the input() function to get the number guessed by the user.
case
number = 28
guess = int(input('请输入数字:'))
if guess==number:
print('恭喜您猜中了')
print('不是每一次您都能猜中')
elif guess <number:
print('您猜的数有点小了')
else:
print("您猜的大了点")
print("猜数完成")
# 当if条件执行完这句话执行
output:
请输入一个数字:50
您猜的大了点
猜数完成
请输入一个数字:22
您猜的数有点小了
猜数完成
请输入一个数字:28
恭喜您猜中了
不是每一次您都能猜中
猜数完成
Note that the if statement includes a colon at the end - we tell Python that a block of statements follows.
Remember that the elif and else parts are optional.
After Python has executed a complete if statement and its associated elif and else clauses, it moves to the next statement in the if statement block. In this example, this block of statements is the main block.
The program starts executing from the main block, and the next statement is the print (' guess done ') statement. After this, Python sees the end of the program and simply ends the run.
You can easily understand the execution process of the conditional statement through the following figure:
The following operators are commonly used in if:
operator | describe |
---|---|
< |
less than |
<= |
less than or equal to |
> |
more than the |
>= |
greater than or equal to |
== |
Equals, compares two values for equality |
!= |
not equal to |
while statement
The while statement allows you to execute a block of statements repeatedly as long as a condition is true. A while statement is an example of a so-called loop statement. The while statement has an optional else clause .
use while statement
while running:
guess = int(input('请输入一个数字 : '))
if guess == number:
print('恭喜你猜到了')
running = False # 让while循环停止
elif guess < number:
print('小了点')
else:
print('大了点')
else:
print('循环结束')
output
请输入一个数字:50
大了点
请输入一个数字:22
小了点
请输入一个数字:28
恭喜你猜到了
循环结束
In this program, we still use the guessing game as an example, but the advantage of this example is that the user can keep guessing until he guesses correctly - so that there is no need to repeat it for each guess as in the previous example program again. This example aptly illustrates the use of the while statement
We moved the input and if statements inside the while loop and set the running variable to True before the while loop started. First, we check if the variable running is True, and then execute the following while-block. After executing the program, check the condition again, which in this case is the running variable.
If it is true, we execute the while-block again, otherwise, we continue with the optional else-block and proceed to execute the next statement.
The else block is only executed when the while loop condition becomes False - this may even be the first time the condition is checked. If your while loop has an else clause, it will always be executed unless your while loop will go on forever and never end
True and False are called boolean types. You can read them equivalently as the values 1 and 0, respectively . Boolean types are important when testing important conditions, they are not real values
The else block is actually redundant, because you can put the statements in it in the same block (same as while), after the while statement, to achieve the same effect.
for loop
for..in is another looping statement that recursively over a sequence of objects uses each item in the queue one by one.
Use the for statement
Case:
for i in range(1, 5):
print(i)
else:
print('循环结束')
output:
1
2
3
4
循环结束
In this program, we print a sequence of numbers. We generate this sequence of numbers using the built-in range function.
All we do is provide two numbers, and range returns a sequence of numbers. The sequence starts at the first number and ends at the second. For example, range(1,5) gives the sequence [1, 2, 3, 4]. By default, the step size of range is 1 . If we provide a third number for range then it will be the step size.
For example, range(1,5,2) gives [1,3]. Remember that range extends up to the second number, i.e. it does not contain the second number
The for loop recurses over this range - for i in range(1,5) is equivalent to for i in [1, 2, 3, 4], which is as if each number (or object) in the sequence was assigned to i, one at a time, then execute the block for each value of i. In this example, we just print the value of i.
Remember, the else part is optional. If else is included, it is always executed once after the for loop ends, unless a break statement is encountered
break statement
The break statement is used to terminate the loop statement, that is, stop the execution of the loop statement even if the loop condition is not called False or the sequence has not been fully recursed.
An important note is that if you terminate from a for or while loop, any corresponding loop else block will not execute.
Case:
while True:
s = input('输入字符串 : ')
if s == 'quit':
break
print ('字符串的长度是', len(s))
print '循环结束'
output:
输入字符串 : I
字符串的长度是 1
输入字符串 : Love
字符串的长度是 4
输入字符串 : You
字符串的长度是 3
输入字符串 : quit
循环结束
In this program, we repeatedly get the user's input, and then print the length of each input. We provide a special condition to stop the program by checking if the user's input is 'quit' . Stop the program by terminating the loop to the end of the program.
The length of the input string is obtained by the built-in len function
continue statement
The continue statement is used to tell Python to skip the remaining statements in the current loop block and continue with the next loop.
Case:
while True:
s = input('输入字符串 : ')
if s == 'quit':
break
if len(s) < 3:
print('太短了')
continue
print('验证通过')
print('循环结束')
# 自此处起继续进行其它任何处理
output:
输入字符串 : I
太短了
输入字符串 : Love
验证通过
输入字符串 : You
验证通过
输入字符串 : quit
循环结束
In this program, we take input from the user, but we only process them if they are at least 3 characters long. So, we use the built-in len function to get the length. If the length is less than 3, we will use the continue statement to ignore the remaining statements in the block . Otherwise, the remaining statements in this loop will be executed, and we can do whatever processing we want here.
while loop diagram
Purely free online learning programming
Scan the code to start learning
Poke the original text👇Online learning