Read Number from Console Input in Python
To read a number from console in Python input by user, you can use input() function.
input() functions enables your Console Python application to read input from user.
Usually input() function reads string from console. Also, Python3 does not differentiate if the input is a string or number. Whatever the user provides as input through the console, it takes in as a String.
Once we get the string input by user in console, we can typecast the input to integer.
Example 1: Read Number/Integer from Console
In this example, we shall read an input from user using input() function. input() function returns a string. int() around the input function, shall typecast the string returned by input() into an integer. Thus n1 and n2 shall have numbers after the user has provided the number in the console.
#read integer from user n1 = int(input('Enter a number: ')) n2 = int(input('Enter another number: ')) print('The sum of two numbers is:', n1+n2)
Run the program and you shall see a prompt for reading
n1. Enter a number and click enter key. Then you shall see the prompt for reading
n2. Enter a number and click enter key. Once we read the two inputs as numbers, we shall add the two numbers and print the result to the console.
Enter a number: 52 Enter another number: 14 The sum of two numbers is: 66
Arithmetic Operation has been performed, because n1 and n2 are integers, and not strings.
Also, you can try printing the type of the variable
n2. Let us try in the following Python program.
#read integer from user n1 = int(input('Enter a number: ')) print(type(n1))
<class 'int'> represents that the variable
n1 is of class type
int, short for integer.
Enter a number: 52 <class 'int'>
In this tutorial of Python Examples, we learned how to read an integer from console: read string using input() and then typecast it using int(); with the help of well detailed Python example programs.