0

I've been working on this small coding exercise in Python for a few hours already:

def collatz(number):
        if number % 2 == 0:
            print(number // 2)
            return number // 2

        elif number % 2 == 1:
            result = 3 * number + 1
            print(result)
            return result

print('Enter a number: ')
try:
    enter = int(input())
except ValueError:
    print('Please type an integer. Try again...')

while enter != 1:
    enter = collatz(enter)

It seems to work properly when a number is entered and when I enter a non-integer value I get the proper response but I keep getting this error after the response:

Enter a number: 
Hello
Please type an integer. Try again...
Traceback (most recent call last):
  File "C:/Users/P1ttstop/PycharmProjects/sweigartLearning/collatzSequence.py", line 17, in <module>
    while enter != 1:
NameError: name 'enter' is not defined

I've been trying to fix this but to my dismay I can't seem to figure it out. What is happening here?

  • 1
    because `enter = int(input())` failed, `enter` is not defined when you come to `while enter != 1:` You should probably put the input code into a loop... – Nick Jan 28 '20 at 02:02

2 Answers2

0

Taken from the Python docs, a NameError exception is:

Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.

And a ValueError exception is:

Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.


You receive a ValueError exception after running this line and inputting the string "Hello":

enter = int(input())

The except block will then handle this error, meaning the enter variable will never be assigned the value "Hello." Since the enter variable was never defined, the following line will produce a NameError:

while enter != 1:
dkhara
  • 695
  • 5
  • 18
0

I have tested code, and modified some part.

def collatz(number):
        if number % 2 == 0:
            print(number // 2)
            return number // 2

        elif number % 2 == 1:
            result = 3 * number + 1
            print(result)
            return result

print('Enter a number: ')
try:
    enter = int(input())
    while enter != 1:
        enter = collatz(enter)
except ValueError:
    print('Please type an integer. Try again...')

Enter a number: hello

Please type an integer. Try again...

Community
  • 1
  • 1
Saisiva A
  • 595
  • 6
  • 24