Back to Python
2026-01-056 min read

The input() Function (Python Programming)

Learn The input() Function (Python Programming) step by step with clear examples and exercises.

Title: The input() Function (Python Programming)

Why This Matters

The input() function is an essential tool in Python programming that enables interactive applications and empowers users to customize their program's behavior. By understanding the input() function, you will be able to build more engaging and dynamic programs catering to user needs.

Prerequisites

Before delving into the input() function, it is essential to have a solid grasp of Python syntax, variables, data types, operators, control flow structures (like if-else statements), and basic functions. Familiarity with these concepts will help you better understand the usage and capabilities of the input() function.

Core Concept

What is the input() function?

The input() function allows a Python program to accept user input as a string from the keyboard. It reads a line from standard input (the keyboard) and returns it as a string, enabling users to type any text, numbers, or expressions enclosed in parentheses, which will be treated as strings by default.

user_input = input("Enter something: ")
print(user_input)

In this example, the program asks the user to enter something and then prints whatever the user types.

How does it work internally?

The input() function relies on Python's built-in sys.stdin object (standard input) to read data from the keyboard. The entered text is stored in a string, which can be assigned to a variable for further processing or display.

Type conversion with the input() function

By default, the input() function returns a string. However, you can convert the user's input to other data types using Python's built-in functions like int(), float(), and bool().

user_number = int(input("Enter an integer: "))
print(type(user_number))

user_float = float(input("Enter a floating point number: "))
print(type(user_float))

user_boolean = bool(input("Enter True or False: "))
print(type(user_boolean))

In this example, the program asks for an integer, a floating-point number, and a boolean value. The user's input is converted to the appropriate data type using the corresponding conversion functions.

Using the input() function in loops

The input() function can be used within loops to repeatedly prompt users for input until a specific condition is met.

numbers = []
while True:
user_number = int(input("Enter an integer (or type 'quit' to stop): "))
if user_number == -1:
break
numbers.append(user_number)
print(numbers)

In this example, the program asks users to enter integers one by one until they type "quit". The entered numbers are stored in a list called numbers.

Worked Example

Let's create a simple calculator that takes two numbers as user input and performs addition, subtraction, multiplication, or division based on the operator entered by the user.

def calculate():
num1 = float(input("Enter first number: "))
operator = input("Enter an operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
result = num1 / num2
else:
print("Invalid operator. Please enter either +, -, *, or /.")
return

print(f"The result is {result}")

calculate()

In this example, the calculate() function takes user input for two numbers and an operator. It performs the appropriate calculation based on the entered operator and prints the result. If the user enters an invalid operator, it displays an error message and returns without performing any calculations.

Common Mistakes

1. Not converting user input to the correct data type

When working with numerical operations, forgetting to convert user input to the appropriate data type can lead to unexpected results or errors. Make sure to use the appropriate conversion functions (int(), float(), etc.) when necessary.

2. Assuming user input is always valid

It's essential to validate user input and handle exceptions gracefully. For example, if you expect a floating-point number but receive an integer instead, your program should be able to handle that situation without crashing.

3. Not providing clear instructions for user input

When asking users for input, make sure to provide clear instructions on the expected format (e.g., "Enter an integer" or "Enter a floating-point number"). This helps reduce confusion and ensures that your program receives the desired data.

4. Ignoring whitespace in user input

When working with text inputs, it's essential to account for possible whitespace at the beginning or end of user input strings. You can use Python's built-in strip() function to remove leading and trailing whitespace from a string.

5. Not handling multiple lines of user input correctly

When you expect multiple lines of user input, make sure to split the input on newline characters (\n) to work with each line individually.

Practice Questions

  1. Write a Python script that takes a user's name as input and greets them accordingly.
  2. Create a program that calculates the area of a rectangle using user-provided length and width.
  3. Build a simple password checker that asks for a user's password, checks it against a predefined value, and provides feedback based on whether the password is correct or not.
  4. Write a program that takes a list of numbers as input from the user and calculates their sum.
  5. Create a program that takes two dates (in the format MM/DD/YYYY) as input from the user and calculates the number of days between them.
  6. Write a program that asks users to enter a series of words, and then prints the longest word entered.
  7. Build a program that takes a string as input and counts the occurrence of each vowel in the string.
  8. Create a program that takes a user's age as input and calculates how many years they have left until they reach retirement (assuming retirement age is 65).
  9. Write a program that asks users to enter a sequence of numbers, and then finds the maximum and minimum values in the sequence.
  10. Create a program that takes a user's weight and height as input and calculates their body mass index (BMI).

FAQ

  1. Why does the input() function return a string by default?

The input() function returns a string because it reads data from the keyboard as text. However, you can convert the user's input to other data types using Python's built-in functions like int(), float(), and bool().

  1. Can I use the input() function to read a file instead of getting user input?

No, the input() function is designed for gathering user input from the keyboard. To read data from a file, you should use Python's built-in open() function.

  1. How can I get multiple lines of user input using the input() function?

To get multiple lines of user input, you can use a loop that repeatedly calls the input() function until the user indicates they have finished entering data (e.g., by typing "done" or "quit").

  1. Is there a way to limit the number of characters a user can enter using the input() function?

Yes, you can use Python's built-in maxlength argument with the input() function to limit the maximum number of characters that a user can enter. For example:

user_input = input("Enter something (max 10 characters): ")[:10]

In this example, the program asks the user to enter something with a maximum of 10 characters, and it stores only the first 10 characters in the user_input variable.

  1. How can I ignore whitespace when reading user input using the input() function?

To ignore whitespace when reading user input, you can use Python's built-in split() function with no arguments to split the input on whitespace and then work with each word individually.

user_input = input("Enter something: ").split()

In this example, the program asks the user to enter something and splits their input into a list of words, ignoring any whitespace between the words.

The input() Function (Python Programming) | Python | XQA Learn