Input in Python

Learn how to take user input from the command line using the input() function

Basic Usage

The input() function reads a line from input, converts it to a string, and returns it.

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

Converting Input

Since all input is read as a string, you often need to convert it:

age = input("Enter your age: ")
age = int(age)  # Convert to integer
print("You will be", age + 1, "next year.")

Multiple Inputs

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

Using map() to Simplify

x, y = map(int, input("Enter two integers: ").split())
print("Product:", x * y)

Input with Lists

# Input: 1 2 3 4 5
numbers = list(map(int, input("Enter numbers: ").split()))
print("You entered:", numbers)

Best Practices

Error Handling Example

try:
    num = int(input("Enter a number: "))
    print("Square:", num * num)
except ValueError:
    print("That was not a valid number!")