Read Integer from Command Line
To read integer from command line in Python, we can use input() builtin function. Since, input() function reads a string from standard input, we can use int() function to convert the string to integer.
The following is a simple code snippet to read an integer into variable x
.
x = int(input())
We can also prompt user via input() function.
x = int(input('Enter an integer : '))
Examples
Read integer from user
In the following example, we read an integer from user into variable x
, using input() and int() functions.
Python Program
try: n = int(input('Enter an integer : ')) print('N =', n) except ValueError: print('You entered an invalid integer')
Output
Enter an integer : 1254 N = 1254
Now, we shall read two integers from user, add them, and print the result to output.
Python Program
try: a = int(input('Enter a : ')) b = int(input('Enter b : ')) output = a + b print('Sum :', output) except ValueError: print('You entered an invalid integer')
Output
Enter a : 5 Enter b : 4 Sum : 9
Conclusion
In this Python Tutorial, we learned how to read an integer from user, using input() and int() function.