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.

DYZ
  • 55,249
  • 10
  • 64
  • 93
gfgk
  • 1
  • 1
  • 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: https://docs.python.org/3/howto/pyporting.html – DYZ Feb 03 '18 at 04:25
  • @DYZ: That looks like the opposite of this question... – ShadowRanger Feb 03 '18 at 04:28
  • https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers – DYZ Feb 03 '18 at 04: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.") – Rahul Kumar Singh Feb 03 '18 at 05:04

2 Answers2

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.")
JoshG
  • 6,472
  • 2
  • 38
  • 61
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.")
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271