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
the for loop shall run 'n' number of times . the second 'n' is the length of the array. the last statement maps the integers to a list and takes input in space separated form . you can also return the array at the end of for loop.
Convert to integers:
Similarly for floating point numbers:
TLDR
input
function, but Python 2'sinput
function does (read the next section to understand the implication).input
is theraw_input
function.Python 2.x
There were two functions to get user input, called
input
andraw_input
. The difference between them is,raw_input
doesn't evaluate the data and returns as it is, in string form. But,input
will evaluate whatever you entered and the result of evaluation will be returned. For example,The data
5 + 17
is evaluated and the result is22
. When it evaluates the expression5 + 17
, it detects that you are adding two numbers and so the result will also be of the sameint
type. So, the type conversion is done for free and22
is returned as the result ofinput
and stored indata
variable. You can think ofinput
as theraw_input
composed with aneval
call.Note: you should be careful when you are using
input
in Python 2.x. I explained why one should be careful when using it, in this answer.But,
raw_input
doesn't evaluate the input and returns as it is, as a string.Python 3.x
Python 3.x's
input
and Python 2.x'sraw_input
are similar andraw_input
is not available in Python 3.x.Solution
To answer your question, since Python 3.x doesn't evaluate and convert the data type, you have to explicitly convert to
int
s, withint
, like thisYou can accept numbers of any base and convert them directly to base-10 with the
int
function, like thisThe second parameter tells what is the base of the numbers entered and then internally it understands and converts it. If the entered data is wrong it will throw a
ValueError
.For values that can have a fractional component, the type would be
float
rather thanint
:Apart from that, your program can be changed a little bit, like this
You can get rid of the
play
variable by usingbreak
andwhile True
.For multiple integer in a single line,
map
might be better.If the number is already known, (like 2 integers), you can use