0

I'm trying to switch a code from Python 2.7.10 to Python 3, and some things aren't working. I just recently was introduced to Python.

choice = 2 while choice != 1 and choice != 0: choice = input("Hello, no.") if choice != 1 and choice != 0: print("Not a good code.") 

How do I change the "!=" into something Python 3 will understand? When I type in 1 or 0, it gives me my "hello, no" invalid print.

4
  • First, learn to indent your code. Second, input in Python3 returns a string. You must convert it to an int before comparing. Third,you may find this document useful: docs.python.org/3/howto/pyporting.html Commented Feb 3, 2018 at 4:25
  • @DYZ: That looks like the opposite of this question... Commented Feb 3, 2018 at 4:28
  • stackoverflow.com/questions/20449427/… Commented Feb 3, 2018 at 4:30
  • choices = 2 choice=str(choices) while choice != '1' and choice != '0': choice = input("Hello, no.") if choice != '1' and choice != '0': print("Not a good code.") Commented Feb 3, 2018 at 5:04

2 Answers 2

1

The input function returns user input as a string. You can convert it to a number using the int and float methods:

choice = 2 while choice != 1 and choice != 0: choice = input("Hello, no.") choice = int(choice) if choice != 1 and choice != 0: print("Not a good code.") 
Sign up to request clarification or add additional context in comments.

Comments

1

input in Python 3 is equivalent to Python 2's raw_input; it reads a string, it doesn't try to eval it. This is because eval of user input is intrinsically unsafe.

If you want to do this safely in Python 3, you can wrap the call to input in int to convert to int, or in ast.literal_eval to interpret arbitrary Python literals without opening yourself up to arbitrary code execution.

import ast choice = 2 while choice != 1 and choice != 0: choice = ast.literal_eval(input("Hello, no.")) if choice != 1 and choice != 0: print("Not a good code.") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.