input() function - get input from the user in Python

In this article, we would discuss input() function in Python v3.9. input() function, a built-in Python function, helps us get input from the user.

By default, input() function reads the input as string unless otherwise instructed. Here, we would discuss how a user can input integer, float and string values with the help of input() function.

input() function – get string input

If we want to obtain a string input from the user. Then,

#Program to get string input from the user

x=input("Enter your Name: ")
print(x)

We have asked the user to input his/her name with a prompt and have stored the input in variable x. Then, we print the name using print() function.

Output –

Enter your Name: XYz
XYz

We would like to add more, a user can also provide numerical input to the above code. And, that would work perfect. The input() function would read the numerical input as a string. And, we won’t be able to perform any arithmetic operation on it. We illustrate it with following code –

#Concatenation

x=input("Enter your first name: ")
y=input("Enter your surname: ")
print(x+y)

We have deliberately put in numerical input i.e. first name — 34 and surname — 65.

Output –

Enter your first name: 34
Enter your surname: 65
3465

The output is self-explanatory. It just reads + as concatenation operator and joins both the strings.

For arithmetic operations we would have do more along with input() function.

input() function – get integer input

To ask a user for integer input, typecast the variable using int() function. For instance –

#Program to get integer input from the user

x=int(input("Enter first number: "))
y=int(input("Enter second number: "))
print(x+y)

Output –

Enter first number: 34
Enter second number: 65
99

Herein, concatenation didn’t happen. The interpreter already knows that we would be storing integer input in our variables x and y. So, it did an arithmetic operation on it.

input() function – get float input

Similarly, for a float input – typecast the variable using float() function. For instance –

#Program to get float input from the user

x=float(input("Enter first number: "))
y=float(input("Enter second number: "))
print(x+y)

Output –

Enter first number: 34.45
Enter second number: 65
99.45

It is worth mentioning here that, a user can provide integer input on a float() function. But, float input while using int() function doesn’t work.

In conclusion, here we discussed how to get string, integer and float input from the user using input() function in Python.

Similar Posts