Python loop and judgment

Keywords: Python less

1.for cycle
The for statement can be used to traverse all elements, such as outputting the characters in the string one by one, outputting the elements in the list one by one, the elements in the tuple, the elements in the collection (pay attention to the order of the elements in the assignment), the keys in the dictionary
1-1.range cycle:

1 for I in range (5): the "range (5) function is to generate a list of 0-4 to determine the number of cycles
2         print(i)
3 "" output:
4 D: \ Python \ venv \ scripts \ python. Exe D: / Python / basic / loop. py
5             0
6             1
7             2
8             3
9             4

This is the list generated from range, which is assigned to i variables from 0. Each assignment is repeated until the end of the list
Tuple mode:

for i in (0,1,2,3,4)
  print(i)  ##The output result is the same as the above, but it is generally not used and not concise.

How to list:

for i in ["j",1,3,"a",5]:
     print(i)

How to string:

for i in "python":
  print(i)

2.while loop
If the condition is true, repeat the same operation. If the condition is not met, skip the loop

while loop condition:

Cycle operation
Example: calculate the added value of 1-10

1 i = 1        ##Assign an initial value to the i variable    
2 num = 0        #Assign an initial value to num variable    
3 while(i<=10):  #Set cycle judgment condition: if i If the variable is less than 10, the condition is true. Execute the statement in the loop, otherwise jump out of the loop
4   num = num + i #Computation statement 
5   i = i + 1   #Give variables i+1 Return to variable i
6 print(num)

Nested loop -- > after the external loop meets the conditions, the executing code begins to execute the internal loop, and so on. If the external loop conditions are also met, the external loop executes again, and so on, until the external loop jumps out.
For example: input 5 scores of two students and calculate the average score respectively

  

 1       j=1                                         # Define initial value of external cycle counter
 2           prompt='Please enter the student's name'                       # Define string variable, which can be called during user input to reduce the trouble of typing Chinese characters
 3           while j<=2:                                 # Define the external loop to execute twice
 4               sum=0                                   # Define the initial score value. The reason why it is defined here is that when the second student enters the score, he can sum Initialize to 0 and receive the scores and
 5               i=1                                     # Define initial value of internal cycle counter
 6               name = raw_input(prompt)               # Receive the student name input by the user and assign it to name variable
 7               while i<=5:                             # Define the internal function cycle 5 times, that is, receive the scores of 5 courses
 8                   print ('Please input number 1.%d Examination results: '%i)   #Prompt the user to enter the score, in which the formatted output is used,%d With the value of i The value of, course 1, course 2
 9                   sum= sum + input()                  # Receive the score entered by the user and assign it to sum
10                   i+=1                                # i Variable increment 1, i Change to 2, continue the loop until i When equal to 6, jump out of the loop
11               avg=sum/(i-1)                           # Calculate the average of the first student sum/(6-1),Assign to avg
12               print name,'The average of%d\n'%avg         # Output student average
13               j=j+1                                   # External loop counter after internal loop execution j Self increase 1, change to 2, and then carry out external circulation
14           print 'Student score input completed!'                     # End of external cycle, prompt input completed!

3. Cycle control
Loop control statement can change the normal execution order of loop

Loop control statement

break statement: jump out of this loop (only one level of loop will jump out of the nested loop)

Continue statement: skip the remaining statements of the current cycle body, retest the cycle state, and enter the next cycle. For example, the number of cycles is 5 times in total. If the fourth time we encounter continue, we will not continue to execute, and directly judge the fifth cycle



4. If elif else > condition determination execution
if condition:

expressions

If the value of condition is True, the contents of the expressions statement will be executed, otherwise the statement will be skipped for further execution.

Example: enter a number to determine

 1     while True:                                        #Establish a dead cycle
 2             try:                                        #Anomaly capture
 3                 num = float(input('Please enter a number:'))  #Keyboard gets a value
 4                 if num == 0:                            #if Determine whether it is equal to 0
 5                     print('The number entered is zero')                #Output if equal to 0
 6                 elif num > 0:                            ##if determines whether it is greater than 0
 7                     print('The number entered is positive')            #Output if greater than 0
 8                 else:                                    #Output if none of the above decisions are consistent else Statement below
 9                     print('The number entered is negative')
10                 break
11             except ValueError:                            #Capture input exceptions
12                 print("The number you entered is invalid!")                #Execute when an exception is caught
13     

Posted by Zyxist on Fri, 06 Dec 2019 02:43:00 -0800