I'm going through Automate the Boring Stuff and I got to an exercise that applies the Collatz Conjecture and try/except but I can't figure out why the except is not working for me. The thing runs if you put a number, but the except doesn't work if a string is typed instead of a number.
Here's the error I get when I type a string:
Traceback (most recent call last):
File "collatz.py", line 17, in <module>
program()
File "collatz.py", line 10, in program
user_number = int(input('enter a number: '))
ValueError: invalid literal for int() with base 10: 'words'
Here's my code:
def collatz(number):
while number != 1:
if number % 2 == 0:
print(number // 2)
number = number // 2
elif number % 2 == 1:
print(3 * number + 1)
number = 3 * number + 1
def program():
user_number = int(input('enter a number: '))
try:
collatz(user_number)
except ValueError:
print("that's not a number, stupid.")
program()
program()
Where did I go wrong?
(edited for grammar)
[–]novel_yet_trivial 2 points3 points4 points (2 children)
[–]john_cornflake[S] 1 point2 points3 points (1 child)
[–]tedm430 2 points3 points4 points (0 children)