Python Basic Tutorial Loop Statements (for while and Nested Loop)

  • 2021-10-11 18:57:26
  • OfStack

A loop can be used to repeat a statement until a condition is met or to traverse all elements.

1 for cycle

Is an for loop, which can traverse the elements of collection data types list, tuple, dict and set.

(1) Loop list

city_list = ['Guangzhou', 'Shenzhen', 'Dongguan', 'Foshan']


city_list = [' Guangzhou ',' Shenzhen ',' Dongguan ',' Foshan ']

for city in city_list:
 print(" The current cities are: {0}".format(city))

The current city is: Guangzhou
The current city is: Shenzhen
The current city is: Dongguan
The current city is: Foshan

(2) Cycle dict


city_dict = {'A':' Guangzhou ','B':' Shenzhen ','S':' Dongguan ','E':' Foshan '}
for code in city_dict.keys():
 city = city_dict[code]
 print("{0} The license plate code of is : Guangdong {1}".format(city,code))

The license plate code of Guangzhou is: Guangdong A
The license plate code of Shenzhen is: Guangdong B
The license plate code of Dongguan is: Guangdong S
Foshan's license plate code is: Guangdong E

(3) Example: Calculate the sum of arithmetic progression

Using the for loop, calculate the sum of the numbers 1-20


sum = 0
for i in range(1,21): # range(1,21) The corresponding interval number is: [1,21)
 sum += i
print(' The sum of the values is %d'%sum)

The sum of the values is 210

2 while cycle

As long as the conditions are met, it will continue to cycle, and when the conditions are not met, it will exit the cycle.

(1) Numerical cycle


n = 0
while(n < 5):
 n+=1
 print(" Current value {0}".format(n))

Current value 1
Current value 2
Current value 3
Current value 4
Current value 5

(2) Example: Calculate the sum of arithmetic progression

Using the for loop, calculate the sum of the numbers 1-20


sum = 0
n = 0
while(n < 20):
 n += 1
 sum += n
print(' The sum of the values is %d'%sum)

The sum of the values is 210

3 Loop nesting

Embed another loop in one loop body, either for loop in while loop or while loop in for loop.

Example: Simulating the Web Site Login Verification Process


n = 5
pwd = "123789"
while (n > 0):
 in_str = input(" Please enter your password: ")
 n -= 1
 if len(in_str) < 6:
  print(" Output password is less than 6 Bit, remaining opportunity {0} Please re-enter! ".format(n))
 if in_str == pwd:
  print(" Login successful! ")
  break
 else:
  print(" Output password error, remaining opportunities {0} Please re-enter! ".format(n))

if n == 0:
 print(" Login failed, please try again later! ")
 

Please enter the password: 123
The output password is less than 6 digits, and the remaining opportunities are 4 times. Please re-enter it!
Output password error, 4 chances remaining, please re-enter!
Please enter the password: 123567
Output password error, 3 chances remaining, please re-enter!
Please enter the password: 123789
Login successful!

Summarize


Related articles: