Gizmobreaker
Posts: 2
Joined: Wed Nov 25, 2020 4:14 pm

input string throws 'name 'Q' is not defined'

Wed Nov 25, 2020 4:41 pm

i apologize, in advance, if this is just me being stupid. I am trying to use Input to get instruction from the user but something is wrong. I am using Raspian OS Buster on a PI 3 B+ and the Thonny IDE with Python 3.7.3. Here's the code:

Code: Select all

import sys
bool_running = True
try:
    while bool_running:
        str_Choice = input("Choose 1 or Q: ")
        print(str_Choice)
        if str_Choice == 'Q': #then we want to Quit
            print("Quit")
            bool_running = False
            sys.exit()
        elif str_Choice == '1': #then we would do something
            ''' In Windows 10, this works
               In Raspian, it has to be without the 's
            '''
              print("You chose: ", str_Choice)
        else:
            print("You have to choose 1 or Q")

except Exception as e:
    print(e)
Oddly, this throws an error when I run it in the terminal and press Q, then Enter. The error text is "name 'Q' is not defined". However, if I run it in the debugger in Thonny, it works fine.

If I use an integer instead of a letter (say, 4), this all works fine.

One curiosity is that if I run it in Windows 10, Python 3.7.8, it works only if the if statements reference string values without quotes (i.e., 1, not '1') but in Raspian the opposite is true.

I must be misunderstanding something but I cannot figure out what that is. What heck am I doing wrong?

Thank you, everyone, and thanks for being patient with me.

User avatar
rpiMike
Posts: 1612
Joined: Fri Aug 10, 2012 12:38 pm
Location: Cumbria, UK

Re: input string throws 'name 'Q' is not defined'

Wed Nov 25, 2020 4:52 pm

What command are you using when run in terminal?

I suspect you are using 'python test.py', you should use 'python3 test.py'.

hippy
Posts: 8924
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: input string throws 'name 'Q' is not defined'

Wed Nov 25, 2020 6:37 pm

Gizmobreaker wrote:
Wed Nov 25, 2020 4:41 pm
One curiosity is that if I run it in Windows 10, Python 3.7.8, it works only if the if statements reference string values without quotes (i.e., 1, not '1') but in Raspian the opposite is true.
That's rather odd but you could try running this on both -

Code: Select all

answer = input("1 or Q :")
print(answer)
print(type(answer))
I suspect however it's the same problem; running with Python 2 rather than Python 3

Gizmobreaker
Posts: 2
Joined: Wed Nov 25, 2020 4:14 pm

Re: input string throws 'name 'Q' is not defined'

Wed Nov 25, 2020 7:45 pm

Exactly correct! Python3 was the answer. I told you it was me being stupid! Thank you, both, very much.
Hippy, with the "Python3" command line, both Windows and Raspian work the same. Quotes are required.

Return to “Python”