笨方法学习Python-习题33: While 循环

while 循环

Python中while语句的一般形式:

while 判断条件:
    语句
while 循环,它所作的和 if 语句类似,也是去检查一个布尔表达式的真假,不一样的是它下面的代码片段不是只被执行一次,而是执行完后再调回到 while 所在的位置,如此重复进行,直到 while 表达式为 False 为止。While 循环有一个问题,那就是有时它会永不结束,当出现该问题时,你可以使用 CTRL+C 来退出当前的无限循环。


下面进行本章练习

i = 0
numbers = []

while i < num:
    print("At the top i is %d" % i)
    numbers.append(i)
    
    i = i + 1
    print("Numbers now: ",numbers)
    print("At the bottom i is %d" % i)
    
print("The numbers: ")

for num in numbers:
    print(num)

我们可以根据所学的知识,再次编写while脚本,观察有何不同

def while_test(num,step):
    i = 0
    numbers = []

    while i < num:
        print("At the top i is %d" % i)
        numbers.append(i)
 
        #i = i + 1
        i += step	
        print("Numbers now: ",numbers)
        print("At the bottom i is %d" % i)
    
    print("The numbers: ")

    for num in numbers:
        print(num)

num = int(input("请输入要循环的数字>>"))
step = int(input("请输入步长>>"))

# 调用函数
while_test(num,step)

for循环和while循环有何不同:for循环适用于已知循环次数,while循环适用于未知循环次数





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值