Why are x
and y
strings instead of ints in the below code?
(Note: in Python 2.x use raw_input()
. In Python 3.x use input()
. raw_input()
was renamed to input()
in Python 3.x)
play = True
while play:
x = input("Enter a number: ")
y = input("Enter a number: ")
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
if input("Play again? ") == "no":
play = False
While in your example,
int(input(...))
does the trick in any case,python-future
'sbuiltins.input
is worth consideration since that makes sure your code works for both Python 2 and 3 and disables Python2's default behaviour ofinput
trying to be "clever" about the input data type (builtins.input
basically just behaves likeraw_input
).Multiple questions require input for several integers on single line. The best way is to input the whole string of numbers one one line and then split them to integers. Here is a Python 3 version:
input()
(Python 3) andraw_input()
(Python 2) always return strings. Convert the result to integer explicitly withint()
.In Python 3.x,
raw_input
was renamed toinput
and the Python 2.xinput
was removed.This means that, just like
raw_input
,input
in Python 3.x always returns a string object.To fix the problem, you need to explicitly make those inputs into integers by putting them in
int
:I encountered a problem of taking integer input while solving a problem on CodeChef, where two integers - separated by space - should be read from one line.
While
int(input())
is sufficient for a single integer, I did not find a direct way to input two integers. I tried this:Now I use num1 and num2 as integers. Hope this helps.