How input() works in Python?

Learn how to prompt the user for input during program execution in Python using the input() method.

How input() works in Python?
How input() function works in Python?

The input() method prompts the user for input, reads the line from input, converts it into a string, and returns it.

Example 1

Code

user_input = input("Enter a string==> ")

print(f"The user input is {user_input}")

print(type(user_input))

Output

Enter a string==> Hello
The user input is Hello
<class 'str'>

Example 2

Even if you enter numerical values, the input() built-in function converts them to strings.

Code

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")

print(type(num1), type(num2))

# User might enter float
sum = float(num1) + float(num2)

# We get a float value
print(f"The sum of {num1} and {num2} is {sum}")

Output

Enter first number: 2
Enter second number: 3
<class 'str'> <class 'str'>
The sum of 2 and 3 is 5.0

The above codes use f-strings. Learn about python f-strings here.

Exercise

Write a Python program to ask the user for an integer and convert it into a floating point. Answer

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe