Python之while语句及相关练习

本文通过多个实例介绍了Python中while循环的应用,包括计数打印、求和、用户登录验证、猜数字游戏及打印乘法表等。这些例子覆盖了从简单到复杂的循环使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • while 条件():
    条件满足时,做的事情1
    条件满足时,做的事情2
#1.定义一个变量,记录循环次数
i = 1
#2.开始循环
while i <= 3:
    #循环内执行的动作
    print('hello python')
    #处理计数器
    i += 1

2.定义死循环,条件永远为真

while True:
    print('hello python')

3.求和:求0-100之间的数字的和

i = 0  #1.定义一个变量记录循环的次数
result = 0 #2.定义结果的变量
while i <= 100: #3.开始循环
    result += i  #4.每次循环都让result和i这个计数器相加
    i += 1 #5.处理计数器
print('和为:%d' %result)

4.用while循环实现用户登录

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次,请稍后再试!')

5.猜数字游戏
1) 系统随机生成一个1~100的数字;
2)用户总共有5次猜数字的机会;
3) 如果用户猜测的数字大于系统给出的数字,打印“too big”;
4) 如果用户猜测的数字小于系统给出的数字,打印"too small";
5) 如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退出循环;

import random
computer=random.randint(1,100)
for i in range (5):
    player=int(input('请输入你猜的数:'))
    if player == computer:
            print('恭喜!')
            exit()
    elif (player > computer):
            print('too big!')
    elif (player < computer):
            print('too small!')
        #print('你还有%d次机会,请重试!' %(4-i))
else:
    print('机会已用完,失败!正确的数为%d' %(computer))

6.输出四种不同形状的星星

row = 5
 while row >= 1:
     col = 1
     while col <= row:
         print('*',end='')
         col += 1
     print('')
     row -= 1
	 *
     **
     ***
     ****
     *****

7.打印9*9乘法表

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值