2.6 The input() Function (BT101CO)

The input() function is the primary way to make a program interactive by allowing it to accept data from the user during execution. In Python, this function pauses the program and waits for the user to type something and press the Enter key.

1. Basic Syntax

The syntax for the input() function is:

Variable_Name = input("Optional Prompt Message")

  • Prompt Message: A string displayed on the screen to tell the user what kind of data is expected.
  • Return Value: Whatever the user types is assigned to the variable on the left.

Example:

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

2. The "String" Rule

A critical concept is that the input() function always returns a string (str), even if the user types a number.

If you type 25, Python treats it as the text "25", not the mathematical value 25. This means you cannot perform arithmetic on it directly without conversion.

3. Type Casting (Conversion)

To use the input as a number (integer or float), you must wrap the input() function inside a conversion function like int() or float(). This is known as Type Casting.

  • For Integers:
    age = int(input("Enter your age: "))
  • For Decimals:
    price = float(input("Enter the price: "))

What happens if you don't cast?

val = input("Enter a number: ")
print(val * 2) 
# If you enter 5, the output is '55' (string repetition), not 10.

4. Reading Multiple Inputs

While input() reads a single line, you can read multiple values at once using the .split() method. This is a common technique for competitive programming and quick data entry.

Example:

# User enters: Ashok 25 Kathmandu
name, age, city = input("Enter Name, Age, and City (separated by space): ").split()

print(f"User {name} is {age} years old and lives in {city}.")

5. Summary Table

Feature Description
Purpose To accept user input from the keyboard.
Default Type Always returns data as a String.
Execution Pauses the program until Enter is pressed.
Arithmetic Requires int() or float() conversion before math.

6. Practical Example: The Interactive "Bill Calculator"

This example combines input(), type casting, and formatted print() to solve a common real-world task.

# Accepting user input
item_name = input("Enter the item name: ")
price = float(input(f"Enter the price of {item_name}: "))
quantity = int(input("How many are you buying? "))

# Calculating the total
total_cost = price * quantity

# Using f-string for a clean output
print(f"\n--- Receipt ---")
print(f"Item: {item_name}")
print(f"Total Amount: ${total_cost:.2f}")

By using input(), you transition from writing static scripts to creating dynamic applications that respond to real-world data.

Practice Quiz