21番茄网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 21番茄网
查看: 720|回复: 0

while循环练习汇总

[复制链接]

650

主题

805

帖子

2706

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2706
发表于 2020-11-19 09:09:36 | 显示全部楼层 |阅读模式
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循环练习汇总  Python基础语法 line2
                               
登录/注册后可看大图


方法二while 后面接 条件语句
import random

# 出拳
punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)
user_choice = ''
user_choice = input('请出拳:(石头、剪刀、布)')  # 请用户输入选择
while user_choice not in punches:  # 当用户输入错误,提示错误,重新输入
    print('输入有误,请重新出拳')
    user_choice = input('请出拳:(石头、剪刀、布)')

while循环练习汇总  Python基础语法 1
                               
登录/注册后可看大图


练习二:九九乘法表: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循环练习汇总  Python基础语法 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循环练习汇总  Python基础语法 1
                               
登录/注册后可看大图


练习四while和 in not in 配合
import random

guess = ''

while guess not in ['正面','反面']:
    print('------猜硬币游戏------')
    print('猜一猜硬币是正面还是反面?')
    guess = input('请输入“正面”或“反面”:')
while循环练习汇总  Python基础语法 1
                               
登录/注册后可看大图


练习五while True 不要 break 的方法

not_bad_word = True
while not_bad_word:
    x = input('请给旺财取个外号:')
    if x == '小狗' or x =='汪汪':  # 只要外号是两个中的一个,就会生气。
        not_bad_word = False
        print('我生气了,不想理你了!')

print('对不起,以后我不会这么叫你了')






上一篇:python中取整数的几种方法
下一篇:循环练习汇总
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|21番茄网 ( 粤ICP备10099428号 ) 奇远富

GMT+8, 2024-4-29 08:15 , Processed in 0.954053 second(s), 34 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表