Python User Input from Keyboard – input() function

Python’s input() function lets your program pause and wait for the user to type something on their keyboard. When the user presses Enter, whatever they typed gets returned as a string value your code can work with. This makes input() essential for building interactive programs, command-line tools, and simple games where you need data from the person running your script.

Unlike many programming concepts, input() is straightforward to use. You call the function, optionally provide a prompt string, and Python gives you whatever the user entered. The main thing to remember is that the data always comes back as a string, so you need to convert it if you want numbers for math operations.

  • input() pauses program execution until the user types and presses Enter
  • All values returned are strings, even if the user types numbers
  • Use int() or float() to convert string input to numeric types
  • EOFError occurs when input() runs out of data to read, such as when piping empty input

Syntax of the input() Function

The input() function has a simple structure. The optional parameter is a prompt string that displays to the user before they type.

variable = input(prompt)

The prompt parameter is optional. If you omit it, Python displays nothing and waits silently. If you include a prompt, that text appears so users know what to do.

Reading User Input in Python

Here is a basic example that asks for the user’s name and then prints a greeting.

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

When you run this program, Python displays the prompt, waits for you to type, and then stores your response in the name variable. Running it might look like this in your terminal:

Enter your name: Alice
Hello, Alice

The Type of User Input

Everything input() returns is a string. This applies even when the user types something that looks like a number. You can confirm this with the type() function.

age = input("Enter your age: ")
print(type(age))
print(age)

Running this code and entering 25 produces output showing that age is a string, not an integer:

Enter your age: 25

25

Converting Input to Numbers

Because input() always returns a string, you need to convert the value before performing arithmetic. Use int() for whole numbers or float() for decimal numbers.

Getting an Integer Input

num = int(input("Enter a number: "))
result = num * 2
print("Double your number is", result)

If the user enters 10, the program converts the string “10” to the integer 10, multiplies it by 2, and prints the result. If you need decimal precision, use float() instead.

price = float(input("Enter a price: "))
discount = price * 0.2
print("Discount amount:", discount)

Note that if someone enters text that cannot be converted, Python raises a ValueError. Always validate input in production code to handle this gracefully.

Handling EOFError with input()

EOFError happens when input() tries to read but finds no data available. This commonly occurs when your script receives piped input that is empty, or when running in certain IDE environments where input is not properly connected.

try:
    data = input("Enter something: ")
    print("You entered:", data)
except EOFError:
    print("No input was provided")

Wrapping input() in a try-except block lets your program continue running if no input is available. This is particularly useful when designing scripts that may run in automated testing environments.

Practical Example: Simple Calculator

Here is a working calculator that accepts two numbers and an operator from the user. It demonstrates how to combine input() with type conversion and conditional logic.

print("Simple Calculator")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")

if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    if num2 != 0:
        result = num1 / num2
    else:
        print("Cannot divide by zero")
        result = None
else:
    print("Invalid operator")
    result = None

if result is not None:
    print("Result:", result)

When you run this script, you can enter two numbers and an operator to see the calculated result. This pattern of gathering input, converting types, and branching on values is common in command-line tools.

Practical Example: Menu Choice

Another common use case is presenting a menu and acting on the user’s selection. The following example shows a simple text-based menu that loops until the user chooses to quit.

print("Welcome to the menu")
print("1. Say hello")
print("2. Say goodbye")
print("3. Quit")

while True:
    choice = input("Choose an option: ")
    if choice == "1":
        print("Hello there!")
    elif choice == "2":
        print("Goodbye!")
    elif choice == "3":
        print("Exiting.")
        break
    else:
        print("Invalid choice, try again.")

This pattern works well for CLI tools where you need to repeatedly prompt for input until a certain condition is met.

Frequently Asked Questions

How do I read input on a single line with multiple values?

You can split a single input line using the split() method. For example, input(“Enter two numbers: “).split() returns a list of strings that you can then convert to integers.

Can input() read passwords without showing the typed characters?

Use the getpass module from the standard library. The getpass.getpass() function works like input() but hides what the user types. This is better for sensitive data like passwords.

What happens if the user just presses Enter without typing anything?

Python returns an empty string “”. Your code should check for this condition if empty input would cause problems in your program logic.

The input() function remains one of the most direct ways to build interactive Python programs. From simple prompts to complex menu systems, it provides the foundation for collecting data from the user at runtime. Remember that all input arrives as a string, so always convert it to the type you need before performing numeric operations.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 244