Reading numbers from Console Input in Python
To read a number from the console using Python input by the user, you can use the input() function.
input() functions allow your Python Console application to read input from the user.
Normally, the input() function reads the string from the console. Also, Python3 doesn’t distinguish whether the input is a string or a number. Whatever the user gives as input through the console, it will receive as a String.
Once we get string input by user in console, we can input as integer.
Example 1: Read Number/Integer from Console
In this example, we will read an input from the user using the input() function. The input() function returns a string. int() around the input function, which will input the string returned by input() into an integer. Hence n1 and n2 will have the 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 will see a prompt to read
n1. Enter a number and click the enter key. You will then see a prompt to read
n2. Enter a number and click the enter key. When we read two numeric inputs, we add 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 operations have been performed, since n1 and n2 are integers, not strings.
Also you can try printing the variable type
n2. Let us try in the following Python program.
#read integer from user n1 = int(input('Enter a number: ')) print(type(n1))
<class 'int'> represent that variable
n1 of class type
intabbreviation for integer.
Enter a number: 52 <class 'int'>
In this guide of Python example, we learned how to read an integer from the console: read the string with input() and then type it with int(); with the help of detailed Python example programs.
Hope this helps!