一. for循环
1.for循环使用的语法:
for 变量 in 序列:
循环要执行的动作
2.例1:100以内的奇数求和
range(stop): 0 - stop-1
range(start,stop): start - stop-1
range(start,stop,step): start - stop-1 step(步长)
sum=0
for i in range(1,101,2):
sum += i
print(sum
3.例2:用户输入一个整型数,求该数的阶乘
num=int(input('请输入一个整数:'))
res=1
for i in range(1,num+1):
res*=i
print('%d的阶乘为%d' %(num,res))
4.例3:有1,2,3,4四个数字,求这四个数字能生成多少互不相同且无重复数字的三位数
count = 0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i != j and j !=k and i != k:
print(i * 100 + j * 10 + k)
count += 1
print('生成%d个无重复的三位数' %count)
5.例4:
用户登陆程序需求:
1. 输入用户名和密码;
2. 判断用户名和密码是否正确? (name=‘root’, passwd=‘westos’)
3. 登陆仅有三次机会, 如果超>过三次机会, 报错提示;
trycount = 0
while trycount < 3:
name = input('用户名: ')
password = input('密码: ')
if name == 'root' and password == 'westos':
print('登录成功')
break
else:
print('登录失败')
print('您还剩余%d次机会' %(2-trycount))
trycount += 1
else:
print('登录次数超过3次,请稍后再试!')
二.break、continue 和exit()
break:跳出整个循环,不会再循环后面的内容
continue:跳出本次循环,continue后面的代码不再执行,但是循环依然继续
exit():结束程序的运行
for i in range(10):
if i == 5:
# break
continue
print('hello python')
# exit()
print(i)
print('hello world')
三. while循环
1.while循环使用的语法:
while 条件():
条件满足时,做的事情1
条件满足时,做的事情2
2.例5
#1.定义一个变量,记录循环次数
i = 1
#2.开始循环
while i <= 3:
#循环内执行的动作
print('hello python')
#处理计数器
i += 1
3.死循环
while True:
print('hello python')
4.例6:while循环求和
i = 0
result = 0
while i <= 100:
result += i
i += 1
print('和为:%d' %result)
5.例7:乘法表
row = 1
while row <= 9:
col = 1
while col <= row:
print('%d * %d = %d\t' %(row,col,col * row),end='')
col += 1
print('')
row += 1
6.例8:猜数字游戏
1).系统随机生成一个1~100的数字;
2).用户总共有5次猜数字的机会;
3).如果用户猜测的数字大于系统给出的数字,打印“too big”;
4).如果用户猜测的数字小于系统给出的数字,打印"too small";
5).如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退出循环;
import random
trycount = 0
computer = random.randint(1,100)
print(computer)
while trycount < 5:
player = int(input('Num:'))
if player > computer:
print('too big')
trycount += 1
elif player < computer:
print('too small')
trycount += 1
else:
print('恭喜')
break