for usage:
for recycling syntax:
for 变量 in range(10):
循环需要执行的代码
Presentation range of usage:
range of usage:
range(stop): 0~stop-1
range(start,stop): start~stop-1
range(start,stop,step): start~stop step(步长)
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(1,11,2)
[1, 3, 5, 7, 9]
>>> range(0,11,2)
[0, 2, 4, 6, 8, 10]
>>>
Examples of presentation for usage:
for i in range(5):
print(i)
#求1~100之间所有偶数之和
sum = 0
for i in range(2,101,2):
sum += i
print(sum)
#求1~100之间所有奇数之和
sum1 = 0
for i in range(1,101,2):
sum1 += i
print(sum1)
num = int(input('Num:'))
res = 1
for i in range(1,num + 1):
res *= i
print('%d的阶乘为:%d' %(num,res))
Another method:
Exit cycle of three methods:
break: jump out of the entire cycle
continue: out of this cycle, the latter continue statements are not executed
exit: exit terminates the program
for i in range(10):
if i == 5:
continue
print(i)
print('hello python')
for i in range(10):
if i == 5:
break
print(i)
print('hello python')
for i in range(10):
if i == 5:
exit()
print(i)
print('hello python')