Conditional control statement if else
First, let's take A simple example: design A program to compare the sizes of two numbers A and B. If A and B are not equal, print the values of the larger numbers. If they are equal, print A.
The Python code is as follows:
if A >= B: print('The larger number is:',A) else: print('The larger number is:',B)
The above is just a very simple example. Generally, the form of Python conditional control statement is:
if Condition1: Action1 elif Condition2: Action2 else: Action3
The above code indicates:
- If Condition1 is True, Action1 will be executed;
- If Condition1 is False, it will continue to judge Condition2;
- If Condition2 is True, Action2 will be executed;
- If Condition2 is False, Action3 is executed.
Points for attention
- A colon is used after each condition: the content after the colon represents the statement block to be executed after the condition is met.
- Use indentation to divide statement blocks. Statements with the same number of indentation form a statement block (IDE will automatically indent).
- There is no switch – case statement in Python.
Conditional control statement instance
Example 1: input two numbers A and B from the console, determine the size, and then output A larger number. If they are equal, output the prompt and value.
#Input data from the console defaults to string type and needs to be cast to int type A = int(input("Please enter the number A:")) B = int(input("Please enter the number B:")) if A > B: print('The larger number is:',A) elif A == B: print('A and B are equal to ',A) else: print('The larger number is:',B)
Execution result:
Please enter the number A:123 Please enter the number B:456 The larger number is: 456
Example 2: input the student number from the console. If the student number is correct, output the test result. If the student number is wrong, output the error message.
#Create a "student number score" dictionary exam_results = {'2018002':95,'2018013':'90','2018023':87} #Receive the student number input from the console, default to string type stu_num = input("Please enter the student number:") #Delete the first and last spaces of the student number to avoid affecting the query stu_num = stu_num.strip() #Judge whether the entered student number exists in the "student number score" dictionary if stu_num in exam_results.keys(): print('Your score is :',exam_results.get(stu_num)) else: print('The student number you entered is incorrect!')
Execution result:
Please enter the student number:2018002 Your score is : 95
for loop statement
There are two kinds of loop statements in Python, for loop and while loop. This section first introduces for loop. Generally, we traverse the items in the sequence through the for loop, where the sequence includes but is not limited to string, list, tuple and dictionary.
The general form of for loop is as follows:
for <item> in <sequence>: <actions>
When < item > in < sequence > is True, execute < actions >.
Example 1: average a set of data.
#Test data set num_set = [98,94,82,67,58,90,86] sumOfNum = 0 #Traversing elements in list, summing for element in num_set: sumOfNum += element #Average and print results average = sumOfNum/len(num_set) print("The average is:%f"%(average))
Execution result:
The average is:82.142857
Example 2: traverse the data sequence through the range() function. The range() function can generate a sequence of numbers. Take the generated sequence as an index, and we can traverse the sequence of numbers. The parameters of the range() function are variable:
- range(n): generate a sequence with steps of 1: 1, 2, 3 N;
- range(m, n): generate a sequence with step length of 1: m, m+1, m+2 N;
- range(m, n, s): generate a sequence of steps S: m, m+s, m+2s X (<=n)
for index in range(4): print("index:",index)
Execution result:
index: 0 index: 1 index: 2 index: 3
Example 3: the for loop traverses the data sequence in combination with range().
#Test data set city_set = ['BeiJin','TianJin','ShangHai','HangZhou','SuZhou'] #Index starts at 0 and traverses in step 2 for index in range(0,len(city_set),2): print("city_set[%d]:%s"%(index,city_set[index]))
Execution result:
city_set[0]:BeiJin city_set[2]:ShangHai city_set[4]:SuZhou
while cycle
Unlike the for loop, the while loop does not operate by traversing the data sequence. The basis of the loop is condition judgment. The general form of the while loop is as follows, that is, when the condition is True, the Action is executed, otherwise it exits.
while Conditon: Action
Example 1: average a set of data.
#Initialize test data num_set = [98,94,82,67,58,90,86] sumOfNum = 0 index = 0 while index < len(num_set): sumOfNum += num_set[index] index += 1 #Average and print results average = sumOfNum/len(num_set) print("The average is:%f"%(average))
Execution result:
The average is:82.142857
break statement
The break statement is used to jump out of the for and while loop bodies, which means the end of the loop.
The following example: check whether there is a number less than 60 in the data set, and print the prompt message and terminate if there is one.
#Initialize test data num_set = [98,94,82,67,58,90,86] for i in range(len(num_set)): if num_set[i] < 60: print("Someone failed!") break else: print(num_set[i])
Execution result:
98 94 82 67 Someone failed!
In practice, the break statement is often used in combination with the while statement to jump out of the loop when the conditions are met. Here is an example:
while True: a = input('Please enter a number:') if int(a) > 100: print('error!!!') break else: print(a)
Execution result:
Please enter a number:23 23 Please enter a number:45 45 Please enter a number:101 error!!!
continue statement
Unlike break, continue does not exit the loop body, but skips the remaining statements of the current loop block to continue the next cycle.
Here's an example: traversing a dataset and encountering a data printing prompt less than 60.
#Initialize test data num_set = [98,94,82,67,58,90,86] for i in range(len(num_set)): if num_set[i] < 60: print("Someone failed!") continue print(num_set[i])
Execution result:
98 94 82 67 Someone failed! 90 86
Pass statement
Python pass is an empty statement, which is generally used as a placeholder and does not perform any actual operation, just to maintain the integrity of the program structure. For the sake of intuition, let's take a less appropriate example:
#Initialize test data num_set = [98,82,67,58,90] for i in range(len(num_set)): if num_set[i] < 60: print("Someone failed!") pass print(num_set[i])
Execution result:
98 82 67 Someone failed! 58 90
As you can see from the above example, the pass statement does nothing. However, in practical application, we will not write code like this, which has no meaning. Pass statement is used for occupation. For example, else statement can not be written, but it is more complete. At this time, the meaning of pass occupation is reflected.
#Initialize test data num_set = [98,94,82,67,58,90,86] for i in range(len(num_set)): if num_set[i] < 60: print("Someone failed!") else: pass