The input() function in Python is used to take user input from the standard input. It waits for the user to type something and press Enter before returning the entered data as a string.

input([prompt])
  • prompt (optional): A string displayed to the user before input is taken. It helps indicate what kind of input is expected;
  • The function always returns the input as a string;
name = input("Enter your name: ")
print(f"Hello, {name}!")

Taking Numeric Input

Since input() always returns a string, if you need numeric input, you must convert it to an integer or float using int() or float().

age = int(input("Enter your age: "))
print(f"In 5 years, you will be {age + 5} years old.")

Taking Floating-Point Input

height = float(input("Enter your height in meters: "))
print(f"Your height is {height} meters.")

Using input() with Multiple Variables

a, b = map(int, input("Enter two numbers separated by space: ").split())
print(f"Sum: {a + b}")

Here, split() breaks the input into a list of strings, and map(int, ...) converts each string to an integer.


Handling input() with Default Values

You can provide a default value using the or operator:

name = input("Enter your name: ") or "Guest"
print(f"Welcome, {name}")

Using input() with Lists

numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print(f"Numbers List: {numbers}")

Handling Errors in input()

If the user enters invalid data, it can cause an error. Using try-except helps prevent crashes.

try:
    num = int(input("Enter an integer: "))
    print(f"You entered: {num}")
except ValueError:
    print("Invalid input! Please enter an integer.")

Reading Multi-Line Input using input()

print("Enter multiple lines (type 'STOP' to end):")

lines = []
while True:
    line = input()
    if line.upper() == "STOP":
        break
    lines.append(line)

print("\nYou entered:")
print("\n".join(lines))

  • input() is used to take user input as a string;
  • Always convert input to the required data type (int, float, bool, etc.);
  • Use split() and map() for multiple inputs;
  • Use try-except to handle errors gracefully;