Python入门之while循环语句及其简单练习

1 while循环语句格式

1.1 while循环语句格式:

"""
while 条件:
    条件满足时,做的事情1
    条件满足时,做的事情2
            ...
"""
#1.定义计数器
i = 0

#2.开始循环
while i < 3:
    #循环内需要做的事情
    print('hello python')

    #处理计数器
    i += 1

1.2 while-else循环语句格式:

trycount=0
 while trycount<3:
     print "login"
     trycount+=1
else:    
     print "bigger than 3"


1.3 定义死循环:

while True:
    print('hello python')

2 while循环语句练习

2.1 练习一:0~100的求和

 i = 0
 sum = 0

while i <= 100:
    sum += i

     i += 1

 print('0~100之间的数字求和结果为: %d' %sum)

在这里插入图片描述
2.2 练习二:用户登陆系统(对比for循环语句)

trycount = 0

while trycount < 3:
    name = input('用户名: ')
    passwd = input('密码: ')
    if name == 'root' and passwd == 'westos':
        print('登录成功!')
        break
    else:
        print('登录失败')
        print('您还剩余%d次机会' %(2-trycount))
        trycount += 1
else:
    print('失败超过3次,请稍后再试!')

在这里插入图片描述
2.3 练习三:while嵌套1

"""
生成如下星形图案
*
**
***
****
*****
"""
 row = 1

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

在这里插入图片描述
2.4 练习四:while嵌套2

"""
生成如下星形图案
*****
****
***
**
*
"""
 row = 1

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

在这里插入图片描述
2.5 练习五:while嵌套3

"""
生成九九乘法表
1 * 1 = 1
1 * 2 = 2  2 * 2 = 4
1 * 3 = 3  2 * 3 = 6  3 * 3 = 9
"""

row = 1

while row <= 9:
    col = 1
    while col <= row:
        print('%d * %d = %d\t' %(row,col,row*col),end='')
        col += 1
    print('')
    row += 1

在这里插入图片描述
2.6 练习六:猜数字

"""
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

在这里插入图片描述
在这里插入图片描述

#########################The End##############################

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值