当程序执行到for循环的时候:让变量在序列中取值,一个一个取,取完为止,每取一个值,执行一次循环体
for num in 'abcdef':
print(num,id(num))
print('===')
#num = 'a'
#print(a,id(a))
#print('===')
#num = 'b'
#print(b,id(b)),
#print('===')
range(N) - N是正整数,产生0 ~ N-1的所有整数
range(M, N) - M,N都是正整数,并且N>M,产生M~N-1的所有整数,循环N-M次
range(M, N, S) - M,N,S都是正整数;产生M~N(每次加S)
注意:xrange是python2.0中的语法,python3.0无效(pycharm中)
for num1 in range(10):
print(num1)
for num2 in range(100, 1000):
print(num2)
for num3 in range(0, 101, 2):
print(num3)
计算1+2+3+...+100的和
sum = 0
for num4 in range(1,101):
sum = sum + num4 #sum += num4
print(sum)
'''
执行过程
sum = 0
num4 = 1 sum = sum + num4
num4 = 2 sum = sum + num4
...
num4 = 100 sum = sum += num4
print(sun)
计算2 * 4 * 6 * 8 * ... *20
product = 1
for num5 in range(2, 21, 2 ):
product = product * num5
print(product)
计算0~100中所有能够被3或者5整除的数的和
sum = 0
for num6 in range(0, 101):
if num6 % 3 ==0 or num6 % 5 == 0:
#print(num6)
sum += num6
print(sum)
当条件语句判断结果一直为True,会造成死循环
当条件语句判断结果一开始就为False,循环一次都不会执行
count = 0
while count < 10:
print('===')
count += 1
print(count)
'''执行过程
count = 0
count < 10 True print('===') count += 1
count = 1
count < 10 True print('===') count += 1
以此类推
count = 10
count < 10 False print(count)
count = 0
while count < 11:
print(count)
count += 1
count = 11
while count < 21:
print(count)
count += 1
count = 2
while count < 41:
print(count)
count += 2
sum = 0
count = 2
while count < 41:
sum += count
count += 2
print(sum)
num = int(input('请输入数字:'))
while num != 100:
num = int(input('请输入数字:'))
print(num)
cmd中ctr+c - 结束程序
import random
random_num = random.randint(0,10)
#randint(M,N)
#产生M~N的随机数
print('随机数',random_num)
print('==============游戏开始==============')
import random
random_num = random.randint(0,100)
num1 = 1
num = int(input('请输入数字'))
while num != random_num:
if num > random_num:
print('偏大')
else:
print('偏小')
num = int(input('请输入数字'))
num1 += 1
print('恭喜猜对',num)
print('猜的次数',num1)
if 0 < num1 < 5:
print('真厉害')
elif 5 <= num1 < 10:
print('勉强过关')
else:
print('你可能是个傻子')
for x in range(5):
if x % 3 == 0:
continue
print(x)
print('=====')
输出结果:
1
=====
2
=====
4
=====
sum = 0
num = 0
while sum <= 100:
num += 1
sum += num
print(num, sum,sum-num)
sum1 = 0
num1 = 1
while True:
sum1 += num1
if sum1 > 100:
break
num1 += 1
print(num1,sum1,sum1-num1)
for 变量 in 序列:
循环体
else:
语句块
while 条件语句:
循环体
else:
语句块
for x in range(5):
print(x)
break
else:
print('循环结束') #0
num = 2
while num < 5:
print(num)
num += 1
break
else:
print(num)
输出结果:2
num = 2
while num < 5:
print(num)
num += 1
else:
print(num)
输出结果:
2
3
4
5
for x in range(5):
for y in range(4):
print(x)
print(y)
输出过程
x = (0,1,2,3,4)
x = 0 y = (0,1,2,3)
y = 0 print(0),print(0)
y = 1 print(0),print(1)
y = 2 print(0),print(2)
y = 3 print(0),print(3)
x = 1 y = (0,1,2,3)
y = 0 print(1),print(0)
y = 1 print(2),print(1)
y = 2 print(3),print(2)
y = 3 print(4),print(3)...
以此类推