Browse Python Topics ▼
Pick a Web Framework

Input and Output

📂 Getting Started 📘 Lesson 5 of 57

Build interactive programs by capturing keyboard input with input() and formatting console output with print(), sep, and end.

Up until this point, our programs have operated on fixed numbers and hardcoded text written directly in the file. But software becomes genuinely useful when it is interactive—when it can accept data from real humans, process that data, and present results back to the user.

In computer science, this is known as I/O (Input/Output):

  • Input (stdin): Data entering your program from the outside world (like keystrokes on a keyboard).
  • Output (stdout): Data leaving your program and displaying in the console or terminal.

In Python, the two fundamental tools that handle this conversation are print() and input().


1. Mastering the print() Function

The print() function is your program’s voice. It takes whatever data you give it, converts it into readable text, and sends it to your terminal screen.

Printing Multiple Items

You can pass multiple items to print(), separated by commas. By default, Python automatically places a single space between each item:

first_name = "Maya"
score = 98
passed = True

print("Student:", first_name, "Score:", score, "Passed:", passed)

Output:

Student: Maya Score: 98 Passed: True

Customizing the Separator with sep

By default, the items passed to print() are separated by a space (sep=" "). You can customize this separator to anything you want using the sep keyword argument:

# Separate with dashes
print("2026", "10", "15", sep="-")

# Separate with slashes for dates
print("10", "15", "2026", sep="/")

# Separate with no spaces at all
print("user", "@", "example.com", sep="")

Output:

2026-10-15
10/15/2026
user@example.com

Controlling Line Endings with end

Normally, every print() call automatically adds a hidden newline character (\n) at the end, moving the cursor to the next line. You can change this behavior with the end parameter:

# Keep printing on the same line
print("Checking database", end="... ")
print("Connected", end="! ")
print("Ready.")

Output:

Checking database... Connected! Ready.

2. Capturing User Input with input()

The input() function pauses your program, displays an optional prompt message, and waits for the user to type something on their keyboard and press Enter. Once they press Enter, the function captures what was typed and assigns it to a variable:

user_name = input("What is your name? ")
print("Hello,", user_name, "- welcome to Python!")

When this script runs, the terminal displays:

What is your name? _

The cursor blinks and waits. If the user types Elena and hits Enter, the program resumes and prints:

Hello, Elena - welcome to Python!

Pro-Tip: Always leave a space at the end of your prompt message inside input("Enter name: "). Without that trailing space, the user’s cursor will be glued right against the colon, making it look cluttered.


3. The #1 Beginner Trap: Everything from input() is a String!

This is the single most common mistake made by new programmers in their first week of learning Python.

The input() function ALWAYS returns text (a string, or str), even if the user types numbers!

Observe what happens when you try to do math with raw input:

# DANGEROUS CODE:
num1 = input("Enter first number: ")   # User types 10
num2 = input("Enter second number: ")  # User types 20

total = num1 + num2
print("The total is:", total)

If the user enters 10 and 20, you might expect the total to be 30. Instead, the program prints:

The total is: 1020

Why? Because num1 is the text "10" and num2 is the text "20". When you use the + operator between two strings, Python does not do arithmetic—it performs string concatenation (gluing the words together into "1020").

Even worse, if you try to multiply num1 * 5.5, Python will crash with a TypeError!


4. Converting Input with Type Casting

To perform mathematical calculations on user input, you must convert the incoming string into a number. This is called type casting (which we cover in full detail in type-casting):

  • int(text): Converts text to a whole integer (e.g., "25" $\rightarrow$ 25).
  • float(text): Converts text to a decimal floating-point number (e.g., "19.99" $\rightarrow$ 19.99).

Here is the correct, safe way to handle numeric input:

# Read as text, then convert to an integer
age_text = input("How old are you? ")
age = int(age_text)

# Now standard math works perfectly!
next_year_age = age + 1
print("Next year, you will be:", next_year_age)

You can also combine both steps into a clean single line:

# Directly wrap input() with int() or float()
item_price = float(input("Enter item price: $"))
quantity = int(input("Enter quantity: "))

total_cost = item_price * quantity
print("Total cost: $", total_cost)

5. Mini-Project: Interactive Restaurant Bill Splitter

Let’s combine everything learned in Stage 1 into a complete, practical command-line application that you can run on your computer:

# ==========================================
# Restaurant Bill & Tip Calculator
# ==========================================

print("=== Welcome to the Tip Calculator ===")

# 1. Gather inputs
bill_amount = float(input("What was the total bill? $"))
tip_percentage = int(input("What percentage tip would you like to give? (15, 18, 20): "))
people_count = int(input("How many people are splitting the bill? "))

# 2. Perform calculations
tip_decimal = tip_percentage / 100
total_tip = bill_amount * tip_decimal
total_bill = bill_amount + total_tip
amount_per_person = total_bill / people_count

# 3. Present formatted output
print("\n--- Receipt Summary ---")
print(f"Total Bill (with tip): ${total_bill:.2f}")
print(f"Each person should pay: ${amount_per_person:.2f}")
print("=======================")

Sample Terminal Run:

=== Welcome to the Tip Calculator ===
What was the total bill? $125.50
What percentage tip would you like to give? (15, 18, 20): 20
How many people are splitting the bill? 4

--- Receipt Summary ---
Total Bill (with tip): $150.60
Each person should pay: $37.65
=======================

Notice :.2f inside the curly braces of f"${total_bill:.2f}"—that tells Python to format the decimal number rounded cleanly to 2 decimal places, perfect for currencies! (You will explore formatted strings in depth in string-formatting).


Summary Checklist

  • print(): Sends output to the terminal screen.
  • sep=" ": Customizes the spacer between multiple printed values.
  • end="\n": Customizes what prints at the end of the statement (change to "" to stay on the same line).
  • input("prompt"): Halts execution and collects text typed by the user.
  • String Conversion: input() always returns text; use int() or float() before performing arithmetic.

Congratulations on completing Stage 1: Getting Started! You know what programming is, how your environment runs, how syntax works, and how to interact with users.

Now, move forward to Stage 2: Variables & Data Types, starting with deep mastery of variables and types.

Test your understanding of Input and Output

Quick interactive practice questions with instant feedback.

Take Quiz →