Input Function

Learn how to use the input() function in Python to take user input and convert it into different data types.

Loading...
Input Function

What is input()?

The input() function lets you take information from the user.

For example:

name = input("Enter your name: ")
print("Hello", name)

When you run this code, you’ll see:

Enter your name:

If you enter:

John

You’ll get:

Hello John

Here’s what happens:

  • input() displays "Enter your name: ".
  • The user enters their name.
  • Python stores the input in the name variable.
  • print() displays the greeting.

input() Always Returns String

There’s one important thing to remember: input() always gives you the user’s input as a string.

For example:

age = input("Enter your age: ")

Even if you enter 27, Python treats 27 as a string, not as a number.

You can check this using type():

age = input("Enter your age: ")
 
print(type(age))
 
# Output:
 
# <class 'str'>

Now, what if you actually want to use the input as a number?

Converting Input to a Number

You can convert the string into a number using int().

age = int(input("Enter your age: "))
 
print(age)
print(type(age))
 
# Output:
# 27
# <class 'int'>

Here, int() converts the string "27" into the number 27.

What if the user enters something that can’t be converted to a number?

Python raises a ValueError.

age = int(input("Enter your age: "))
 
# If you type "abc", Python raises a ValueError

You can also use float() when you need a decimal number:

price = float(input("Enter the price: "))
 
print(price)
print(type(price))
 
# If you enter 99, the output is:
# 99.0
# <class 'float'>

Now, let’s combine what we’ve learned so far:

name = input("What's your name? ")
age = int(input("How old are you? "))
 
print("Hello", name)
print("You are", age, "years old.")
 
# Output:
# Hello John
# You are 27 years old.

Now our program can actually interact with the user.


👉 Next tutorial: Python Strings