Python3_loop

 

Code:

print('------------------------------------------------------')
# for...in. Loop: Iterate over each element in the list or tuple in turn
names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

print('------------------------------------------------------')
num = 0
for x in [1,2,3,4,5,6,7,8,9,10]:
	num = num + x
print('1 + 2 + 3 + 4 .. + 10 =',num)

print('------------------------------------------------------')
print('list(range(5)) :',list(range(5)))
#Python provides a range() function that can generate a sequence of integers, which can then be converted to a list through the list() function

print('------------------------------------------------------')
num = 0
for x in range(101):
	num = num + x
print(num)

print('------------------------------------------------------')
#while loop, as long as the conditions are met, it will continue to loop, and exit the loop when the conditions are not met
#Calculate the sum of all odd numbers within 100
num = 0
n = 99
while n > 0:
	num = num + n
	n = n - 2
print(num)

print('------------------------------------------------------')
#break: The break statement can exit the loop early
n = 1
while n <= 100:
	if n > 10: # When n = 11, the condition is satisfied, execute the break statement
		print('break!')
		break # break statement will end the current loop
	print(n)
	n = n + 1
print('END')

print('------------------------------------------------------')
#continue: During the loop, you can also use the continue statement to skip the current loop and start the next loop directly
n = 0
while n < 10 :
	n = n + 1
	if n % 2 == 0 : # If n is even, execute continue statement
		continue # The continue statement will directly continue the next cycle of the loop, and the subsequent print() statement will not be executed
	print(n)
	

 

 

TestCode:

# -*- coding: utf-8 -*-
'''
Please use a loop to print Hello, xxx! for each name in the list in turn:
'''
L = ['Bart', 'Lisa', 'Adam']
for name in L :
	print('Hello,%s!'%name)

print('''
Infinite loop:
num = 1
while num > 0 :
	num = num + 1
print(num)
''')

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326662832&siteId=291194637