小白教程

 找回密码
 立即注册

while语句

发布者: 小白教程

while只要条件为真,语句就可以重复执行语句块。一个while说法是所谓的一个例子循环语句。一条while语句可以有一个可选的else子句。

示例(另存为while.py):

number = 23
running = True

while running:
    guess = int(input('Enter an integer : '))

    if guess == number:
        print('Congratulations, you guessed it.')
        # this causes the while loop to stop
        running = False
    elif guess < number:
        print('No, it is a little higher than that.')
    else:
        print('No, it is a little lower than that.')
else:
    print('The while loop is over.')
    # Do anything else you want to do here

print('Done')

输出:

$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

这个怎么运作

在此程序中,我们仍在玩猜谜游戏,但是优点是允许用户继续猜测,直到他正确猜出为止-无需像上一节中那样重复为每个猜想重复运行该程序。 。这恰当地演示了该while语句的用法

我们移动inputif语句内部while循环,并设置变量runningTruewhile循环之前。首先,我们检查变量running是否为True,然后继续执行相应的while-block执行该块后,将再次检查条件,在这种情况下为running变量。如果为true,则再次执行while块,否则继续执行可选的else块,然后继续执行下一条语句。

elsewhile循环条件变为时执行False-这甚至可能是第一次检查该条件。如果有循环else子句while,则除非您使用break语句退出循环,否则它将始终执行

TrueFalse被称为布尔类型,你可以认为他们是等同于价值10分别。

C / C ++程序员注意事项

请记住,您可以elsewhile循环添加一个子句

上一篇:控制流if语句下一篇:for语句

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 06:37 , Processed in 0.018429 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部