Why does this code not input integers? Everything on the web says to use raw_input(), but I read on Stack Overflow (on a thread that did not deal with integer input) that 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

14 Answers 11

up vote 164 down vote accepted

Python 2.x

There were two functions to get user input, called input and raw_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,

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

The data 5 + 17 is evaluated and the result is 22. When it evaluates the expression 5 + 17, it detects that you are adding two numbers and so the result will also be of the same int type. So, the type conversion is done for free and 22 is returned as the result of input and stored in data variable. You can think of input as the raw_input composed with an eval call.

>>> data = eval(raw_input("Enter a number: "))
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

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.

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = raw_input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <type 'str'>)

Python 3.x

Python 3.x's input and Python 2.x's raw_input are similar and raw_input is not available in Python 3.x.

>>> import sys
>>> sys.version
'3.4.0 (default, Apr 11 2014, 13:05:11) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <class 'str'>)

Solution

To answer your question, since Python 3.x doesn't evaluate and convert the data type, you have to explicitly convert to ints, with int, like this

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

You can accept numbers of any base and convert them directly to base-10 with the int function, like this

>>> data = int(input("Enter a number: "), 8)
Enter a number: 777
>>> data
511
>>> data = int(input("Enter a number: "), 16)
Enter a number: FFFF
>>> data
65535
>>> data = int(input("Enter a number: "), 2)
Enter a number: 10101010101
>>> data
1365

The 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.

>>> data = int(input("Enter a number: "), 2)
Enter a number: 1234
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '1234'

Apart from that, your program can be changed a little bit, like this

while True:
    ...
    ...
    if input("Play again? ") == "no":
        break

You can get rid of the play variable by using break and while True.

PS: Python doesn't expect ; at the end of the line :)

upvote
  flag
Is there any other way, like a function or something so that we dont need to convert to int in 3.x other than doing explicit conversion to int?? – Shreyan Mehta
upvote
  flag
@ShreyanMehta eval would work, but don't go for that unless you have pressing reasons. – thefourtheye
upvote
  flag
Could you please add a tl;dr version to the beginning of the answer? It's a long answer, and I believe many will not bother to read it, and will just use input() and eval(input()) – Elazar

input() (Python 3) and raw_input() (Python 2) always return strings. Convert the result to integer explicitly with int().

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

Pro tip: semi-colons are not needed in Python.

In Python 3.x, raw_input was renamed to input and the Python 2.x input 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:

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

Also, Python does not need/use semicolons to end lines. So, having them doesn't do anything positive.

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:

num = input()
num1 = 0
num2 = 0

for i in range(len(num)):
    if num[i] == ' ':
        break

num1 = int(num[:i])
num2 = int(num[i+1:])

Now I use num1 and num2 as integers. Hope this helps.

upvote
  flag
This looks very interesting. However, isn't i destroyed when the for loop is exited? – Hosch250
upvote
  flag
@hosch250 When a loop is exited, the value of the index variable (here, i) remains. I tried this piece out, and it works correctly. – Aravind

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.

 p=raw_input()
    p=p.split()      
    for i in p:
        a.append(int(i))

For multiple integer in a single line, map might be better.

arr = map(int, raw_input().split())

If the number is already known, (like 2 integers), you can use

num1, num2 = map(int, raw_input().split())

Yes, in python 3.x, raw_input is replaced with input. In order to revert to old behavior of input use:

eval(input("Enter a number: "))

This will let python know that entered input is integer

upvote
  flag
Is this correct? – user3155368
upvote
  flag
Yes, you may try please – Waseem Akhtar
upvote
  flag
This will let python know that entered input is integer, it could be much worse things than an integer. – Padraic Cunningham
def dbz():
    try:
        r = raw_input("Enter number:")
        if r.isdigit():
            i = int(raw_input("Enter divident:"))
            d = int(r)/i
            print "O/p is -:",d
        else:
            print "Not a number"
    except Exception ,e:
        print "Program halted incorrect data entered",type(e)
dbz()

Or 

num = input("Enter Number:")#"input" will accept only numbers

Python 3.x has input() function which returns always string.So you must convert to int

python 3.x

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

python 2.x

In python 2.x raw_input() and input() functions always return string so you must convert them to int too.

x = int(raw_input("Enter a number: "))
y = int(input("Enter a number: "))

Convert to integers:

my_number = int(input("enter the number"))

Similarly for floating point numbers:

my_decimalnumber = float(input("enter the number"))

While in your example, int(input(...)) does the trick in any case, python-future's builtins.input is worth consideration since that makes sure your code works for both Python 2 and 3 and disables Python2's default behaviour of input trying to be "clever" about the input data type (builtins.input basically just behaves like raw_input).

Taking int as input in python: we take a simple string input using:

input()

now we want int as input.so we typecast this string to int. simply using:

int(input())

In Python 3.x. By default the input function takes input in string format . To convert the it int integer you need to include int(input())

x=int(input("Enter the number"))

By default the input function takes input as string format

for other data type you have to cast the user input

In Python 2 we use raw_input() function. it waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input 
x = float(raw_input("Enter a float number: ")) #float input 
x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use input() function which return a user input value

x = input("Enter a number: ") #String input

if you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input 

if you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

if you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

if you enter a string for eval cast

NameError: name ' ' is not defined

Those error also applicable for python 2

Not the answer you're looking for? Browse other questions tagged or ask your own question.