Skip to main content
Editor

Python Input and Output: print(), input(), and Formatting

Beginner15 min4 exercises90 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/4 exercises

Every program needs a way to talk to the outside world. A weather app shows temperatures. A game displays your score. A calculator prints answers. All of these use output.

In Python, print() is your main tool for showing information to the user. It seems simple at first, but it has powerful options that let you control exactly how your output looks.

In this tutorial, you'll learn advanced print() techniques, formatting tricks for clean output, and how input() reads what the user types. By the end, you'll be able to create polished, professional-looking output.

You already know print("Hello") displays text. But print() can handle multiple values at once. Just separate them with commas, and Python prints them all with spaces in between.

Think of print() like a waiter reading off your order. You hand them several items, and they announce each one with a pause between them.

Printing multiple values with commas
# Printing multiple values
name = "Alice"
age = 25
city = "Paris"
print(name, age, city) # Alice 25 Paris
print("Name:", name) # Name: Alice
print("Age:", age, "years") # Age: 25 years
Output
Alice 25 Paris
Name: Alice
Age: 25 years

Notice something helpful: Python automatically adds a space between each value. You also don't need to convert numbers to strings. The print() function handles that for you.


By default, print() puts a space between each value. The sep parameter lets you change that separator to anything you want. It stands for "separator."

Imagine you're stringing beads on a necklace. The sep is the knot you tie between each bead. You choose what goes between the items.

Using sep to control what goes between values
# Default separator is a space
print("A", "B", "C") # A B C
# Custom separators
print("A", "B", "C", sep="-") # A-B-C
print("A", "B", "C", sep=" | ") # A | B | C
print("A", "B", "C", sep="") # ABC (no separator)
print("A", "B", "C", sep="\n") # Each on a new line
Output
A B C
A-B-C
A | B | C
ABC
A
B
C

The sep parameter is perfect for building formatted output like dates, file paths, or CSV data without doing string concatenation yourself.

Practical uses of sep
# Practical uses of sep
year, month, day = 2025, 3, 15
print(year, month, day, sep="-") # 2025-3-15
# Build a file path
print("home", "user", "docs", sep="/") # home/user/docs
# Create CSV-like output
print("Alice", 25, "Paris", sep=",") # Alice,25,Paris
Output
2025-3-15
home/user/docs
Alice,25,Paris

Every time print() finishes, it adds a newline character at the end. That's why each print() call starts on a new line. The end parameter lets you change what comes after the output.

Think of end like the punctuation at the end of a sentence. By default, Python hits "Enter" after each print. You can change that to a space, a comma, or nothing at all.

Using end to control line breaks
# Default end is a newline
print("Hello")
print("World")
# Output:
# Hello
# World
print() # blank line
# Custom end - keep printing on the same line
print("Hello", end=" ")
print("World")
# Output: Hello World
print("Loading", end="...")
print("Done!")
# Output: Loading...Done!
Output
Hello
World

Hello World
Loading...Done!
Using end in a loop
# Print items on the same line using a loop
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(fruit, end=" ")
print() # Final newline to clean up
# Output: apple banana cherry date
Output
apple banana cherry date

How Do You Combine sep and end Together?

You can use sep and end in the same print() call. This gives you full control over both what goes between values and what comes at the very end.

Using sep and end together
# Combine sep and end
print("A", "B", "C", sep=" -> ", end=" [DONE]\n")
# Output: A -> B -> C [DONE]
# Build a progress bar effect
print("Step 1", "Step 2", "Step 3", sep=" > ", end="\n\n")
print("All steps complete!")
Output
A -> B -> C [DONE]
Step 1 > Step 2 > Step 3

All steps complete!

How Do You Create Aligned and Formatted Output?

Real programs need output that's easy to read. Tables, receipts, and reports all need columns that line up neatly. Python gives you several ways to achieve this.

The simplest approach uses the .ljust(), .rjust(), and .center() string methods. These pad a string with spaces to reach a target width.

Aligning text with ljust() and rjust()
# Right-align numbers for a clean column
print("Item".ljust(15), "Price".rjust(8))
print("-" * 24)
print("Coffee".ljust(15), "$4.50".rjust(8))
print("Sandwich".ljust(15), "$8.99".rjust(8))
print("Cookie".ljust(15), "$2.75".rjust(8))
Output
Item               Price
------------------------
Coffee             $4.50
Sandwich           $8.99
Cookie             $2.75

For more control, use f-strings with format specifiers. Inside the curly braces, you can set the width and alignment of each value.

f-string alignment specifiers
# f-string alignment
# < left-align, > right-align, ^ center
print(f"{'Name':<15} {'Score':>8}")
print(f"{'-' * 24}")
print(f"{'Alice':<15} {95:>8}")
print(f"{'Bob':<15} {87:>8}")
print(f"{'Charlie':<15} {92:>8}")
Output
Name               Score
------------------------
Alice                 95
Bob                   87
Charlie               92
A formatted multiplication table
# Building a multiplication table
print(" ", end="")
for i in range(1, 4):
print(f"{i:>4}", end="")
print()
print("-" * 14)
for row in range(1, 4):
print(f"{row} |", end="")
for col in range(1, 4):
print(f"{row * col:>4}", end="")
print()
Output
     1   2   3
--------------
1 |   1   2   3
2 |   2   4   6
3 |   3   6   9

How Does the input() Function Work in Python?

Output is only half the story. Most programs also need to receive information from the user. In Python, the input() function pauses the program and waits for the user to type something.

Think of input() like a form field on a website. The program displays a prompt, the user types their answer, and the program stores that answer in a variable.

Ask a question with input()
name = input("What is your name? ")
print("Hello,", name)

Press Run: the program stops at input() and waits. Type your name, press Enter, and it carries on with your answer in name.

The input() function always returns a string, even if the user types a number. This is an important detail that catches many beginners off guard. Run this and type a number:

input() always returns a string
age = input("How old are you? ")
print(type(age)) # always <class 'str'>
print(age + 10) # TypeError: a string and a number cannot be added

How Do You Convert User Input to Numbers?

Since input() always returns a string, you need to convert it when you expect a number. Wrap input() with int() for whole numbers or float() for decimals.

Converting input to numbers
age = int(input("How old are you? "))
print("In 10 years you will be", age + 10)
price = float(input("Price of the item: "))
print("Tax:", round(price * 0.08, 2))

What Are Common Output Patterns in Python Programs?

Professional programs use recognizable output patterns. Menus, headers, receipts, and progress indicators all follow predictable formats. Learning these patterns makes your programs feel polished.

Pattern: Menu display
# Pattern 1: A menu display
print("=" * 30)
print(" RESTAURANT MENU")
print("=" * 30)
print("1. Burger $8.99")
print("2. Pizza $12.50")
print("3. Salad $7.25")
print("=" * 30)
Output
==============================
    RESTAURANT MENU
==============================
1. Burger         $8.99
2. Pizza          $12.50
3. Salad          $7.25
==============================
Pattern: Formatted report
# Pattern 2: A simple report
title = "Sales Report"
print(title.center(30, "="))
print()
print(f"{'Product':<15} {'Units':>7} {'Revenue':>8}")
print("-" * 30)
products = [
("Widgets", 150, 1500.00),
("Gadgets", 89, 2670.00),
("Gizmos", 234, 4680.00),
]
for name, units, revenue in products:
print(f"{name:<15} {units:>7} {revenue:>8.2f}")
print("-" * 30)
total_rev = sum(r for _, _, r in products)
print(f"{'Total':<15} {'':<7} {total_rev:>8.2f}")
Output
=========Sales Report=========

Product           Units  Revenue
------------------------------
Widgets             150  1500.00
Gadgets              89  2670.00
Gizmos              234  4680.00
------------------------------
Total                    8850.00
Pattern: An interactive calculator
# Pattern 3: A program that asks questions
print("Welcome to the Calculator!")
print("Enter two numbers to add.")
print()
num1 = float(input("First number: "))
num2 = float(input("Second number: "))
print(f"Result: {num1} + {num2} = {num1 + num2}")

Practice Exercises

Time to practice! These exercises focus on print() formatting. Try each one before checking hints.

Exercise 1: Print with a Custom Separator
Write Code

Print the words "red", "green", and "blue" separated by - (space dash space) using the sep parameter of print().

Expected output:

red - green - blue

Use a single print() call with the sep parameter.

# Print "red", "green", "blue" with " - " as the separator
Exercise 2: Print Items on the Same Line
Write Code

Use a for loop to print the numbers 1 through 5 on the same line, separated by spaces. Add an empty print() at the end to finish the line.

Expected output:

1 2 3 4 5

Use the end parameter inside the loop. Be careful not to add a trailing space after 5.

# Print numbers 1 through 5 on the same line
for i in range(1, 6):
# Use end parameter to stay on the same line
pass # Replace this line
print() # Final newline
Exercise 3: Create a Multiplication Table
Write Code

Create a multiplication table for numbers 1 through 3. Each product should be right-aligned and take up 4 characters of width. Print a header row and a separator line.

Expected output:

1   2   3
   -----------
1 |   1   2   3
2 |   2   4   6
3 |   3   6   9

Use f-string alignment ({value:>4}) to right-align numbers in 4-character columns.

# Print the header row
print(" ", end="")
for i in range(1, 4):
print(f"{i:>4}", end="")
print()
# Print the separator
print(" -----------")
# Print each row of the table
# Your code here
Exercise 4: Print a Formatted Receipt
Write Code

Create a formatted receipt with the following items and prices. Use f-string alignment to left-align item names (20 characters wide) and right-align prices (8 characters wide, 2 decimal places). Include a header, separator, and total.

Items:

  • Laptop: 999.99
  • Mouse: 29.50
  • Keyboard: 74.99
  • Expected output:

    ============================
          TECH STORE
    ============================
    Item                   Price
    ----------------------------
    Laptop                999.99
    Mouse                  29.50
    Keyboard               74.99
    ----------------------------
    Total                1104.48
    ============================
    # Create the receipt
    items = [
    ("Laptop", 999.99),
    ("Mouse", 29.50),
    ("Keyboard", 74.99),
    ]
    # Print the header
    # Print column labels
    # Print each item
    # Print the total

    Summary: Python Input and Output

    Here's a quick reference of everything you learned:

    ConceptSyntaxExample
    Print multiple valuesprint(a, b, c)print("Hi", name)
    Custom separatorsep="..."print(1, 2, 3, sep="-") gives 1-2-3
    Custom endingend="..."print("Hi", end=" ") stays on same line
    Left-alignf"{val:<width}"f"{name:<20}"
    Right-alignf"{val:>width}"f"{price:>8.2f}"
    Centerf"{val:^width}"f"{title:^30}"
    User inputinput("prompt")name = input("Name: ")
    Convert inputint(input())age = int(input("Age: "))

    Key takeaway: print() is far more powerful than just displaying text. With sep, end, and f-string formatting, you can create clean, professional output, and input() always hands you a string to convert.

    What's Next?

    Now that you can create polished output, you're ready to control the flow of your programs. In the next tutorials, you'll learn about if statements and loops: the tools that let your programs make decisions and repeat actions.

    Harder problems

    More problems on this topic: Python Basics

    Related Tutorials

    Was this tutorial helpful?