In Python, input() is a built-in function that reads user input from standard input and returns the input content as a string.

Function Syntax

input([prompt])

Parameters:

  • prompt: Optional parameter, the prompt message displayed to the user.

Any user input is returned as a string, excluding the newline character.

input() Function Examples

The following code prompts the user to enter their name and stores it in the variable name:

name = input("What's your name? ")
print(f"Hello, {name}!")

Program Output

What's your name? Jack Chan
Hello, Jack Chan!

The input() function always returns a string, so type conversion is needed for numbers:

number = int(input())    # Integer
number = float(input())  # Floating-point number

Convert to boolean value:

answer = input("Continue? (y/n): ").lower()
continue_flag = answer == 'y' or answer == 'yes'  # Convert to boolean
print(f"Continue: {continue_flag}")

Program Output

Continue? (y/n): yes
Continue: True

Input multiple values:

numbers = input("Enter multiple numbers (separated by spaces): ")

# Convert to integer list
int_list = [int(num) for num in numbers.split()]
print(f"Converted to integers: {int_list}")

Safe Input Handling

Often, it's important to consider whether user input is valid:

number = int(input("Enter a number: "))
print(number)
Enter a number: a
Traceback (most recent call last):
  File "D:\hocn\Desktop\t.py", line 1, in <module>
    number = int(input("Enter a number: "))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'a'

The user might enter an invalid value that doesn't match the prompt. If the program doesn't account for this, it could crash unexpectedly.

A safer approach:

while True:
    try:
        number = int(input("Enter an integer: "))
        print(f"You entered: {number}")
        break
    except ValueError:
        print("Invalid input, please enter an integer!")

EOFError Handling

When the input() function reads EOF (End of File), it triggers EOFError. This often occurs when running a program with input redirection. For example:

# Program expects 3 lines of data
a = input()
b = input()
c = input()

print(a, b, c)

Save the following content to data.txt:

1
2

Run the program with input redirection:

python main.py < data.txt

Since data.txt contains only 2 lines of data but the program calls input() 3 times, the program will throw an EOFError exception on the third input() call.