Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialaaron roberts
2,004 PointsHelp with Exceptions and While Loops
I am just practicing trying to use Exceptions and While Loops at the same time and I have ran into a problem.
try:
number = int(input("choose a number below 10. "))
while number > 10:
number = int(input("choose smaller than 10! "))
except ValueError:
print("error")
number = int(input("you must choose a number. "))
while number > 10:
number = int(input("you must choose a number below 10. "))
print("you chose {}.".format(number))
else:
print("you chose {}".format(number))
This block of code runs how I would like it to apart from when the user inputs two strings in a row. My guess is that when the script enters into the except there is still the possibility of another ValueError. I feel like the only way of getting round this is to include an unlimited amount of "except ValueError:" blocks but this surely is not the way.
My question is, is this the best way to write this code and is the problem fixable? Thanks :)
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsThere are many ways to make the code more concise. Once metric is to look for comparisons done more that once, remembering Don't Repeat Yourself. If an invalid answer occurs in the except
block then it will cause and error within the error and will not be handled.
# clear passing condition
valid_answer = False
# loop until passing
while not valid_answer:
try:
number = int(input("choose a number below 10. "))
if number < 10:
valid_answer = True
else:
print("Number not smaller than 10! ")
except ValueError:
print("error")
print("you must choose a number. ")
else:
print("you chose {}".format(number))
Post back if you wish more help. Good luck!!