简体   繁体   中英

python while loop with break statement

Can please somebody tell me, what the reason the break statement in this context is.

What would be the difference if i remove the breake statement from the code

i am new in python, many thanks in advance!

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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