259

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
smci
  • 32,567
  • 20
  • 113
  • 146
  • [asking-the-user-for-input-until-they-give-a-valid-response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Patrick Artner Sep 13 '18 at 20:50

10 Answers10

392

Solution

Since Python 3, input returns a string which 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'

For values that can have a fractional component, the type would be float rather than int:

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

Differences between Python 2 and 3

Summary

  • Python 2's input function evaluated the received data, converting it to an integer implicitly (read the next section to understand the implication), but Python 3's input function does not do that anymore.
  • Python 2's equivalent of Python 3's input is the raw_input function.

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 the input and stored in the 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'>)
user
  • 1,220
  • 1
  • 12
  • 31
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 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 Apr 09 '16 at 06:19
  • @ShreyanMehta `eval` would work, but don't go for that unless you have pressing reasons. – thefourtheye Apr 09 '16 at 07:01
  • 3
    @thefourtheye at least use [`ast.literal_eval`](https://docs.python.org/3/library/ast.html#ast.literal_eval) for that. It does not have the security concerns of `eval`. – spectras Apr 06 '18 at 12:48
  • I don't understand the point of the other comments here. Calling a function would take the same amount of work as calling `int`. If you mean, something that combines the `int` conversion work with the `input` getting work, it's easy to create that yourself. – Karl Knechtel Mar 24 '23 at 20:56
53

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: "))
Georgy
  • 12,464
  • 7
  • 65
  • 73
35

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())
Georgy
  • 12,464
  • 7
  • 65
  • 73
user1341043
  • 351
  • 3
  • 3
19

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: "))
Georgy
  • 12,464
  • 7
  • 65
  • 73
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
13

Multiple questions require multiple integers to be entered on a single line. The best way is to enter the entire string of numbers line by line and split them into integers. Here is the Python 3 version:

a = []
p = input()
p = p.split()      
for i in p:
    a.append(int(i))

You can also use list comprehensions:

p = input().split("whatever the seperator is")

To convert all input from string to int we do the following:

x = [int(i) for i in p]
print(x, end=' ')

List elements should be printed in straight lines.

pppery
  • 3,731
  • 22
  • 33
  • 46
gumboy
  • 131
  • 1
  • 2
7

Convert to integers:

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

Similarly for floating point numbers:

my_decimalnumber = float(input("enter the number"))
xlm
  • 6,854
  • 14
  • 53
  • 55
Hemanth Savasere
  • 155
  • 1
  • 2
  • 12
7
n=int(input())
for i in range(n):
    n=input()
    n=int(n)
    arr1=list(map(int,input().split()))

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.

ravi tanwar
  • 598
  • 5
  • 16
3

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.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Aravind
  • 47
  • 3
  • This looks very interesting. However, isn't `i` destroyed when the `for` loop is exited? –  May 23 '14 at 16:33
  • `@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 May 24 '14 at 15:18
  • 1
    For this kind of input manipulation, you can either `num1, num2 = map(int, input().split())` if you know how much integers you will encounter or `nums = list(map(int, input().split()))` if you don't. – 301_Moved_Permanently Jul 12 '18 at 12:58
2
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
Sanyal
  • 864
  • 10
  • 22
1

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

Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221