小白教程

 找回密码
 立即注册

中断语句

发布者: 小白教程

break声明是用来打破循环语句的出即停止循环语句的执行,即使循环条件尚未成为False或物品的序列尚未完全遍历。

一个重要的注释是,如果你打破的出forwhile循环,任何对应的循环else是块执行。

示例(另存为break.py):

while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    print('Length of the string is', len(s))
print('Done')

输出:

$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something : use Python!
Length of the string is 11
Enter something : quit
Done

这个怎么运作

在此程序中,我们反复获取用户的输入并每次打印每个输入的长度。通过检查用户输入是否为,我们提供了一种特殊条件来停止程序 'quit'我们通过停止程序打破循环并到达程序的结束。

使用内置len函数可以找到输入字符串的长度

请记住,该break语句也可以与for循环一起使用

Swaroop的诗意Python

我在这里使用的输入是我写的一首小诗:

Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!

continue声明

continue语句用于告诉Python跳过当前循环块中的其余语句,并继续执行循环的下一个迭代。

示例(另存为continue.py):

while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    if len(s) < 3:
        print('Too small')
        continue
    print('Input is of sufficient length')
    # Do other kinds of processing here...

输出:

$ python continue.py
Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit

这个怎么运作

在此程序中,我们接受来自用户的输入,但是仅当输入字符串的长度至少为3个字符时,我们才会对其进行处理。因此,我们使用内置len函数来获取长度,如果长度小于3,则使用continue语句跳过块中的其余语句。否则,将执行循环中的其余语句,并执行我们此处要执行的任何类型的处理。

请注意,该continue语句也适用于for循环。

概括

我们已经看到了如何使用三种控制流语句- ifwhilefor连同其相关联breakcontinue报表。这些是Python中最常用的一些部分,因此,使它们适应是必不可少的。

上一篇:for语句下一篇:函数

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

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

Powered by Discuz! X3.4

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

返回顶部