Python input(): Get User Input from the Keyboard

The input() function takes user input as a string. It’s useful for interactive programs, handling user responses, and collecting data dynamically.

Example

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

Output: _(User enters “Alice”)_

Enter your name: Alice  
Hello, Alice

The function pauses execution until the user provides input.

Syntax

input(prompt)
  • prompt (optional) → A string displayed to the user before input.
  • Returns → Always returns a string (even if the user enters a number).

1. Reading Numbers with input()

Since input() returns a string, convert it to an integer or float if needed.

age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)

If the user enters "25", it’s converted to 25 before calculation.

2. Handling Multiple Inputs in One Line

Use .split() to read multiple values at once.

x, y = input("Enter two numbers: ").split()
x, y = int(x), int(y)
print("Sum:", x + y)

Input:

10 20

Output:

Sum: 30

Useful for handling space-separated input.

3. Providing a Default Value with or Operator

If the user presses Enter, use a default value.

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

If the user enters nothing, "Guest" is used instead.

4. Handling User Input Errors with try-except

Avoid crashes by validating input.

try:
    num = int(input("Enter a number: "))
    print("Double:", num * 2)
except ValueError:
    print("Invalid input! Please enter a number.")

Prevents errors if the user enters non-numeric data.

Key Notes

  • Always returns a string – convert it for numeric operations.
  • Can take multiple inputs with .split().
  • Use or for default values when input is empty.
  • Handle errors with try-except to avoid crashes.

By using input(), you can make interactive programs, collect user data, and handle input efficiently. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top