I am working on a collatz sequence code in python. The code should give me a sequence of numbers that end in 1. The code I have here does that when I enter a number.
try:
number = int(input('Pick a number'))
except ValueError:
print('Error! input a number')
def collatz(number):
if number % 2 == 0:
x = number // 2
return x
else:
x = 3 * number + 1
return x
while number != 1:
number = collatz(number)
print(number)
However, when I try to invoke the try and except function by entering a letter,I get the desired error message but I also get a NameError.
Traceback (most recent call last):
File "/home/PycharmProjects/collatz/collatz.py", line 14, in <module>
while number != 1:
NameError: name 'number' is not defined
Error! input a number *Desired Error Message*
I dont get this error when I remove the try and except function. I have tried defining 'name' as a global variable and also played around with the indentation but nothing seems to work. I would greatly appreciate any kind of help.
I am using python 3.6.