Python 控制流之 while循环和break语句

目录

while 循环

break 语句

总结

参考文档


Python是一种流行的编程语言,它有很多特性和优点。

其中之一就是它的控制流语句,它可以让程序根据不同的条件或循环执行不同的操作。

在这篇文章中,我们将介绍另外两种常用的控制流语句:

while循环和break语句。

while 循环

while循环是一种条件循环语句,它可以让程序重复执行某个代码块,直到一个条件不成立。while循环的基本结构如下:


while condition:
    # do something while condition is True

其中,condition是一个布尔表达式,它可以是一个变量,一个比较运算符(如==, !=, <, >等),一个逻辑运算符(如and, or, not等),或者它们的组合。如果condition为True,则执行while后面缩进的代码块;如果condition为False,则退出循环。

例如,我们可以用 while 循环来计算一个数的阶乘:


# get a positive integer from user input
n = int(input("Enter a positive integer: "))
factorial = 1 # initialize the factorial variable to 1
i = 1 # initialize the loop counter to 1

while i <= n: # loop until i is greater than n
    factorial = factorial * i
    i = i + 1

print(n, "! =", factorial) # print the result

break 语句

break语句是一种跳出语句,它可以让程序提前结束当前的循环。break语句通常和if语句配合使用,来判断是否满足某个终止条件。break语句的基本结构如下:


for item in iterable:
    if condition:
        break # exit the loop if condition is True
    # do something with item

或者


while condition:
    if another_condition:
        break # exit the loop if another_condition is True
    # do something while condition is True

其中,condition 和 another_condition 都是布尔表达式;item 是一个临时变量;iterable 是一个可迭代对象。

例如,我们可以用 while 循环和 break 语句来实现一个猜数字游戏:


import random # import the random module to generate a random number

# generate a random number between 1 and 10 and assign it to answer
answer = random.randint(1, 10)
guess = None

while True: # start an infinite loop
    guess = int(input("Guess a number between 1 and 10: "))
    if guess == answer: # check if the guess is equal to the answer
        print("You got it!")
        break # exit the loop
    elif guess < answer: # check if the guess is less than the answer
        print("Too low.")
    else: # check if the guess is greater than the answer
        print("Too high.")

总结

在这篇文章中,我们介绍了另外两种常用的Python控制流语句:while 循环和break 语句。它们可以让程序根据不同的条件或循环执行不同的操作。

参考文档

PS:

本文首发于公众号: 程序熵, 更多精彩文章请点击关注 code-shang

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值