简体   繁体   English

python while循环与break语句

[英]python while loop with break statement

Can please somebody tell me, what the reason the break statement in this context is. 可以请别人告诉我,在这种情况下break语句是什么原因。

What would be the difference if i remove the breake statement from the code 如果我从代码中删除breake语句,会有什么区别

i am new in python, many thanks in advance! 我是python的新手,非常感谢!

while True:
   try:
      x = int(raw_input("Please enter a number: "))
      break
   except ValueError:
      print "Oops!  That was no valid number.  Try again..."

The idea behind this is that it retrieves a string from the user with raw_input , and then tries to convert it to an integer. 其背后的想法是它使用raw_input从用户检索一个字符串,然后尝试将其转换为整数。 If the conversion is successful, it breaks out of the loop. 如果转换成功,它将退出循环。 If the conversion fails, it throws an exception, jumps over the break statement into the except block, and then goes back to the top of the loop to ask for the number again. 如果转换失败,它将引发异常,将break语句跳过到except块中,然后返回循环的顶部再次询问该数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM