Python——while循环语句

19 篇文章 0 订阅

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件(condition):
    执行语句(statements)……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
当判断条件假 false 时,循环结束。

实例:
count = 0
while count < 9:
    print('The count is:%d' %count)
    count = count + 1
print("Good bye!")

在这里插入图片描述

无限循环

如果条件判断语句永远为 true,循环将会无限的执行下去,如下实例:

while True:
    num=input('enter a number:')
    print('your number is ',num)
print ('循环结束!')

在这里插入图片描述

练习

计算1到100的和

i = 0
result = 0
while i <= 100:
    result += i
    i += 1
print('The result is %d' %result)

结果

The result is 5050

计算1到100之间的偶数和

i = 0
result = 0
while i <= 100:
    if i%2 ==0:
        result += i
    i += 1
print('The result is %d' %result)

结果

The result is 2550
循环嵌套
row = 1
while row <=5:
    col=1
    while col<=row:
        print('*',end='')
        col +=1
    print('') #换行
    row +=1

运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值