在Python中使用Break条件

In many use cases, or due to certain business rules, we need to exit a loop in any programming language. Or, we need to stop a particular loop and continue with the rest of the code. 

在许多用例中,或者由于某些业务规则,我们需要使用任何编程语言退出循环。 或者,我们需要停止特定的循环并继续其余的代码。

This article will help you to understand the use of a break in Python which is mainly used to exit the loops in python programming.

本文将帮助您了解Python中中断的用法,该中断主要用于退出python编程中的循环。

To achieve this we need to use "break" keyword while running a loop. 

为此,我们需要在运行循环时使用“ break”关键字。

Let's take a very simple example of how to use a break in Python programming language. 

让我们举一个非常简单的示例,说明如何使用Python编程语言中的中断。

Example :

范例:

j= 1
for i in range (6):
j=j*2
print ('i= ',i, 'j=',j)
if j==32:
break 

If we execute the above code in any Python interpreter, then we will see the following result :

如果我们在任何Python解释器中执行上述代码,那么我们将看到以下结果:

So let's try to understand the code without adding the break statement. 

因此,让我们尝试在不添加break语句的情况下理解代码。

j= 1
for i in range (6):
j=j*2
print ('i= ',i, 'j=',j)
  

Now we see the code execute without any break. The loop starts from 1 till 5 as we have provided the range as "6" so starting from 0 till 5 the loop will execute :

现在,我们看到代码执行无间断。 循环从1到5开始,因为我们将范围设置为“ 6”,所以从0到5开始,循环将执行:

If we compare the code with a break keyword, we have given an argument as if the result of "j" will be 32, then end the execution of the code so that the loop will run till range 5, as at this point the result of "j" is "32". 

如果将代码与break关键字进行比较,我们将给出一个参数,好像“ j”的结果将为32,然后结束代码的执行,以便循环将运行到范围5,此时结果为“ j”的“ 32”。

This article was to explain and show you a simple programme on how to use a break statement in Python. I hope I've achieved just that.

本文旨在说明并向您展示一个有关如何在Python中使用break语句的简单程序。 我希望我已经做到了。

Thank you for reading my article, please feel free to leave me some feedback or to suggest any future topics.

感谢您阅读我的文章,请随时给我一些反馈或提出任何未来的话题。

I'll be looking forward to hearing from you – Swadhin Ray (Sloba)

我期待着您的回音-Swadhin Ray(Sloba)

For more information about me, please check out my Experts Exchange Profile page.

有关我的更多信息,请查看我的Experts Exchange个人资料页面。

翻译自: https://www.experts-exchange.com/articles/31032/Using-Break-condition-in-Python.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值