I have this simple code:
var = 1
while var == 1 :
try:
num = int(raw_input("Enter a number :"))
except ValueError:
print "Thats not a number!"
continue
try:
num2 = int(raw_input("Enter another number :"))
except ValueError:
print "Thats not a number!"
continue
print "Sum of previous 2 inputs:="+str(num+num2)
print "Good bye!"
Now first continue statement does the job, but the second one, not. Because it goes back at the top of loop, but I need it to go back where second exception was caught, so it would ask to enter second number again, not first number.
Any ideas?
You can factor out entering a number to a function – this spares you writing the same code twice:
def input_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
print "That's not a valid integer!"
...
num = input_int("Please enter a number: ")
num2 = input_int("Please enter another number: ")
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.