python(for循环)

“”"
C java
sum = 0
for(i=1;i<=100;i++)
sum += 1;

Python:
for 循环使用的语法
for 变量 in range(10):
循环需要执行的代码
“”"
“”"

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]

range(stop): 0~stop-1
range(start,stop): start~stop-1
range(start,stop,step): start~stop step(步长)
“”"

#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))

你可能感兴趣的:(python(for循环))