How To Take Integer Input From Command Line In Python

In this notebook, we will look at how to take Integer input from command line in Python 3 and Python 2. For taking string input from command line in Python, check out How To Take String Input From Command Line In Python

Integer Input From Command Line In Python 2

Python raw_input() allows taking input from command line, but by default all the inputs are treated as strings.

In [1]:
userinput = raw_input("Enter Integer Number!\n")
print("You entered %d"%userinput)
Enter Integer Number!
5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-6e2b3ab536e9> in <module>()
      1 userinput = raw_input("Enter Integer Number!\n")
----> 2 print("You entered %d"%userinput)

TypeError: %d format: a number is required, not str

The reason we got above error is "userinput" variable contains a string but not a number.

To fix this, we will have to convert the input to integer before assigning to a variable.

In [2]:
userinput = int(raw_input("Enter Integer Number!\n"))
print("You entered %d"%userinput)
Enter Integer Number!
5
You entered 5

Float Input From Command Line In Python 2

Similarly we can tweak our previous code to take a Floating point number as input.

In [3]:
userinput = float(raw_input("Enter Floating Point Number!\n"))
print("You entered %f"%userinput)
Enter Floating Point Number!
5.6
You entered 5.600000

Integer Input From Command Line In Python 3

Similarly we can use above code snippets in Python 3 by replacing the Python input function raw_input() with input().

In [4]:
userinput = int(input("Enter Integer Number!\n"))
print("You entered %d"%userinput)
Enter Integer Number!
5
You entered 5

Float Input From Command Line In Python 3

In [5]:
userinput = float(raw_input("Enter Floating Point Number!\n"))
print("You entered %f"%userinput)
Enter Floating Point Number!
5.6
You entered 5.600000

Related Notebooks