|
while循环练习汇总
练习一:当输入的内容不是石头剪刀布时,电脑会提醒'输入有误,请重新出拳',并重新出拳。
方法一,while 后接 True:
import random
punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)
while True:
user_choice = input('请出拳(石头,剪刀,布选择一个):')
if user_choice not in punches:
print('输入有误,请重新出拳')
else:
break
方法二,while 后面接 条件语句:
import random
# 出拳
punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)
user_choice = ''
user_choice = input('请出拳:(石头、剪刀、布)') # 请用户输入选择
while user_choice not in punches: # 当用户输入错误,提示错误,重新输入
print('输入有误,请重新出拳')
user_choice = input('请出拳:(石头、剪刀、布)')
练习二:九九乘法表:http://www.21fanqie.com/thread-72-1-1.html
while嵌套,注意break的使用位置
i=1
while i<=9:
j=1
while j<=9:
print('{}*{}={}'.format(j,i,j*i),end=' ')
if i==j:
break
j+=1
print('')
i+=1
练习三:while 后接一个条件,注意break的使用位置,和两个else的使用位置。
n=0
while n<3:
username = input("请输入用户名:")
password = input("请输入密码:")
if username == 'abc' and password == '123':
print("登录成功")
break
else:
n=n+1
print("输入有误")
else:
print("你输错了三次,登录失败")
练习四:while和 in 或 not in 配合
import random
guess = ''
while guess not in ['正面','反面']:
print('------猜硬币游戏------')
print('猜一猜硬币是正面还是反面?')
guess = input('请输入“正面”或“反面”:')
练习五:while True 不要 break 的方法
not_bad_word = True
while not_bad_word:
x = input('请给旺财取个外号:')
if x == '小狗' or x =='汪汪': # 只要外号是两个中的一个,就会生气。
not_bad_word = False
print('我生气了,不想理你了!')
print('对不起,以后我不会这么叫你了')
|
上一篇:python中取整数的几种方法下一篇:循环练习汇总
|