How to Input Integers Using Input in Python

How can I read inputs as numbers?

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

Convert input str to int in python

By default, the input type is string. To convert it into integer, just put int before input. E.g.

number = int(input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: "))
print(type(number))

Sample of the output:

Please guess what number I'm thinking of. HINT: it's between 1 and 30: 30
<class 'int'> # it shows that the input type is integer

ALTERNATIVE

# any input is string
number = input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: ")
try: # if possible, try to convert the input into integer
number = int(number)
except: # if the input couldn't be converted into integer, then do nothing
pass
print(type(number)) # see the input type after processing

Sample of the output:

Please guess what number I'm thinking of. HINT: it's between 1 and 30: 25    # the input is a number 25
<class 'int'> # 25 is possible to convert into integer. So, the type is integer

Please guess what number I'm thinking of. HINT: it's between 1 and 30: AAA # the input is a number AAA
<class 'str'> # AAA is impossible to convert into integer. So, the type remains string

How to input two integers in a same line?

In Python 3, the input() method will always return a string. Your provided code snippet tries to split that input, and the split() function defaults to splitting on a space character.

The map() function takes a function (in this case, the int function), and applies that function to each part of the enumerable returned by the split() function.

So, if you were to write a, b = map(int, input().split(" ")), and then the user entered 123 456, you would have a == 123 and b == 456.

Let's take this as an example: a, b = map(int, input().split())

This is what's going to happen:

  1. The input() function gets executed, and let's say that the user enters 123 456
  2. This gets interpreted as "123 456", and then gets passed into the split function, like this: "123 456".split() which returns a list that looks like this: ["123", "456"].
  3. Now you can sort of imagine that the code looks like this: map(int, ["123", "456"]), which might be a bit easier to reason about.
  4. What's going to happen now is that the map function will take its first argument (the int function), and apply that to each element of the ["123", 456"] list (that is, "123" and "456").
  5. The map() function returns an enumerable, which you in this case can think of as looking like the result of [int("123"), int("456")], which results in [123, 456]
  6. The unpacking of the assignment happens. You can think of that like this: a, b = [123, 456]

How can I limit the user input to only integers in Python

Your code would become:

def Survey():

print('1) Blue')
print('2) Red')
print('3) Yellow')

while True:
try:
question = int(input('Out of these options\(1,2,3), which is your favourite?'))
break
except:
print("That's not a valid option!")

if question == 1:
print('Nice!')
elif question == 2:
print('Cool')
elif question == 3:
print('Awesome!')
else:
print('That\'s not an option!')

The way this works is it makes a loop that will loop infinitely until only numbers are put in. So say I put '1', it would break the loop. But if I put 'Fooey!' the error that WOULD have been raised gets caught by the except statement, and it loops as it hasn't been broken.

Get a list of numbers as input from the user

In Python 3.x, use this.

a = [int(x) for x in input().split()]

Example

>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>>

entering int or float using input()

If your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?



Related Topics



Leave a reply



Submit