Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python program behaves differently in python shell vs terminal

I have a simple Python program that asks yes or no question and I validate that input. If I run this Python shell, it runs fine. If I enter invalid characters it loops back to top of while.

However, if I run this in the terminal window and try to enter an invalid character it errors as shown below.

endProgram = 0
while endProgram != 1:
    userInput = input("Yes or No? ");
    userInput = userInput.lower();

    while userInput not in ['yes', 'no']:
        print("Try again.")
        break

    endProgram = userInput == 'no'

enter image description here

like image 609
Rod Avatar asked Jun 23 '26 18:06

Rod


1 Answers

Looks like your RPi is using Python 2; the input function does an eval there.
input in Python 3 is equivalent to raw_input in Python 2. (See PEP-3111)

Ideally, you should change your RPi interpreter to Python 3. Failing that, you can make it version-agnostic like so:

try:
    input = raw_input
except NameError:
    pass
like image 74
tzaman Avatar answered Jun 25 '26 08:06

tzaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!