python中while语句的练习题

本节练习题:

  • 猜数字游戏
  • 用户登录程序需求
  • 打印四种不同排序方法的星星
  • 打印九九乘法口诀表
练习1:猜数字游戏
     1. 系统随机生成一个1~100的数字;
     2. 用户总共有5次猜数字的机会;
     3. 如果用户猜测的数字大于系统给出的数字,打印“too big”;
     4. 如果用户猜测的数字小于系统给出的数字,打印"too small";
     5. 如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退出循环;

注意:如果想让电脑显示出所给数据,就不要把print(computer)注释掉

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('Congratulation!')
        break
        print('Please try again!')

实验结果

  • 一次性猜对
    python中while语句的练习题_第1张图片
  • 多次情况都猜错
    python中while语句的练习题_第2张图片
  • 没有注释掉print(computer),这是为了方便验证是否猜对数字。实际玩的时候都需要注释掉
    python中while语句的练习题_第3张图片
练习2:用户登陆程序需求
    1. 输入用户名和密码;
    2. 判断用户名和密码是否正确? (name='root', passwd='westos')
    3. 为了防止暴力破解, 登陆仅有三次机会, 如果超过三次机会,报错提示; 

注意:while循环与for循环的区别是,while循环要有一个计数器

trycount = 0
while trycount < 3:
    name = input('UserName:')
    passwd = input('Password:')
    if name == 'root' and passwd == 'westos':
        print('Login success')
        break
    else:
        print('Login failed')
        print('%d chance last' %(2 - trycount))
        trycount += 1
else:
    print('Please try later!')

登陆成功
python中while语句的练习题_第4张图片
登陆失败
python中while语句的练习题_第5张图片

练习3:打印星星(1)

python中while语句的练习题_第6张图片

练习4:打印星星(2)

python中while语句的练习题_第7张图片

练习5:打印星星(3)

python中while语句的练习题_第8张图片

练习6:打印星星(4)

注意:在第一个print中一定要在单引号中使用空格,否则就会变为练习4所示结果
python中while语句的练习题_第9张图片

练习7:打印九九乘法表

python中while语句的练习题_第10张图片

你可能感兴趣的:(Python)