2  Basic Input and Output

2.1 Welcome to Python I/O!

This tutorial will teach you how to interact with users through input and output operations. You’ll learn how to display information using print() and collect data using input() to create interactive programs!

2.2 The print() Function

The print() function is your primary tool for displaying information to users. It’s one of the first things you’ll use in Python!

Basic Printing

# Simple print statement
print("Hello, World!")

# Printing numbers
print(42)
print(3.14159)

# Printing boolean values
print(True)
Hello, World!
42
3.14159
True

Printing Multiple Items

You can print multiple items by separating them with commas:

# Print multiple items (separated by space by default)
print("Python", "is", "awesome!")

# Print different data types together
name = "Alice"
age = 25
print("Name:", name, "Age:", age)

# Print numbers and strings
print("The answer is", 42)
Python is awesome!
Name: Alice Age: 25
The answer is 42

Customizing the Separator

Use the sep parameter to change what appears between items:

# Default separator is a space
print("apple", "banana", "cherry")

# Custom separator
print("apple", "banana", "cherry", sep=", ")

# Using different separators
print("2025", "11", "07", sep="-")
print("Hello", "World", sep=" | ")
print("one", "two", "three", sep="...")
apple banana cherry
apple, banana, cherry
2025-11-07
Hello | World
one...two...three

Customizing the End Character

By default, print() adds a newline at the end. You can change this with the end parameter:

# Default behavior (newline at end)
print("First line")
print("Second line")

print("---")

# Custom end character
print("Same line", end=" ")
print("continued here!")

print("Count: ", end="")
print(100)
First line
Second line
---
Same line continued here!
Count: 100

Printing Special Characters

# Newline character \n
print("Line 1\nLine 2\nLine 3")

# Tab character \t
print("Name:\tAlice\nAge:\t25\nCity:\tNew York")

# Backslash
print("Path: C:\\Users\\Documents")

# Quotes inside strings
print("She said, \"Hello!\"")
print('He\'s learning Python')
Line 1
Line 2
Line 3
Name:   Alice
Age:    25
City:   New York
Path: C:\Users\Documents
She said, "Hello!"
He's learning Python

2.3 String Formatting

Python offers several ways to format strings for better output.

F-String Formatting Options

# Number formatting
pi = 3.14159265359
print(f"Pi: {pi}")
print(f"Pi (2 decimals): {pi:.2f}")
print(f"Pi (4 decimals): {pi:.4f}")

# Padding and alignment
name = "Alice"
print(f"|{name:>10}|")  # Right align in 10 characters
print(f"|{name:<10}|")  # Left align in 10 characters
print(f"|{name:^10}|")  # Center align in 10 characters

# Large numbers with commas
population = 7800000000
print(f"World population: {population:,}")

# Percentage
score = 0.875
print(f"Score: {score:.1%}")
Pi: 3.14159265359
Pi (2 decimals): 3.14
Pi (4 decimals): 3.1416
|     Alice|
|Alice     |
|  Alice   |
World population: 7,800,000,000
Score: 87.5%

2. The format() Method

An older but still valid approach:

name = "Charlie"
age = 28

# Using format()
print("Name: {}, Age: {}".format(name, age))

# With positional arguments
print("{0} is {1} years old. {0} likes Python!".format(name, age))

# With named arguments
print("Hello, {name}! You are {age}.".format(name="Diana", age=22))
Name: Charlie, Age: 28
Charlie is 28 years old. Charlie likes Python!
Hello, Diana! You are 22.

3. String Concatenation

The simplest approach (but least flexible):

first_name = "John"
last_name = "Doe"

# Using + operator
full_name = first_name + " " + last_name
print("Full name: " + full_name)

# Must convert numbers to strings
age = 35
print("Age: " + str(age))
Full name: John Doe
Age: 35

2.4 The input() Function

The input() function allows you to collect data from users, making your programs interactive!

Basic Input

# Simple input
name = input("What is your name? ")
print(f"Hello, {name}!")

Note: Interactive input examples won’t run in this document. Try them in your Python environment!

Understanding input()

Important facts about input(): - Always returns a string (even if user enters a number) - Displays the prompt message to the user - Waits for user to type something and press Enter - Can be stored in a variable for later use

# The input is always a string!
user_input = input("Enter something: ")
print(f"You entered: {user_input}")
print(f"Type of input: {type(user_input)}")

Getting Numeric Input

Since input() returns a string, you need to convert it to work with numbers:

# Getting an integer
age_str = input("Enter your age: ")
age = int(age_str)  # Convert to integer
print(f"Next year you'll be {age + 1}")

# Getting a float
height_str = input("Enter your height in meters: ")
height = float(height_str)  # Convert to float
print(f"Your height is {height:.2f} meters")

# Shorter version (convert immediately)
temperature = float(input("Enter temperature in Celsius: "))
fahrenheit = (temperature * 9/5) + 32
print(f"{temperature}Β°C = {fahrenheit:.1f}Β°F")

Multiple Inputs

# Getting multiple pieces of information
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
age = int(input("Enter your age: "))

print(f"\nProfile:")
print(f"Name: {first_name} {last_name}")
print(f"Age: {age}")

2.5 Practical Examples

Let’s combine input and output in real-world scenarios!

Example 1: Greeting Program

print("=== Welcome! ===")
name = input("What's your name? ")
favorite_color = input("What's your favorite color? ")

print(f"\nNice to meet you, {name}!")
print(f"I love {favorite_color} too!")

Example 2: Simple Calculator

print("=== Simple Calculator ===")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

print(f"\nResults:")
print(f"{num1} + {num2} = {num1 + num2}")
print(f"{num1} - {num2} = {num1 - num2}")
print(f"{num1} Γ— {num2} = {num1 * num2}")
print(f"{num1} Γ· {num2} = {num1 / num2:.2f}")

Example 3: Shopping Receipt

print("=== Store Receipt Generator ===")
item_name = input("Item name: ")
price = float(input("Price: $"))
quantity = int(input("Quantity: "))

subtotal = price * quantity
tax = subtotal * 0.08  # 8% tax
total = subtotal + tax

print("\n" + "="*30)
print("RECEIPT")
print("="*30)
print(f"Item: {item_name}")
print(f"Price: ${price:.2f}")
print(f"Quantity: {quantity}")
print("-"*30)
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"Total: ${total:.2f}")
print("="*30)

Example 4: Personal Info Card

print("=== Create Your Info Card ===\n")
name = input("Full Name: ")
age = int(input("Age: "))
city = input("City: ")
hobby = input("Favorite Hobby: ")

print("\n" + "β”Œ" + "─"*38 + "┐")
print(f"β”‚ {'PERSONAL INFO CARD':^36} β”‚")
print("β”œ" + "─"*38 + "─")
print(f"β”‚ Name:  {name:<29} β”‚")
print(f"β”‚ Age:   {age:<29} β”‚")
print(f"β”‚ City:  {city:<29} β”‚")
print(f"β”‚ Hobby: {hobby:<29} β”‚")
print("β””" + "─"*38 + "β”˜")

2.6 Common Pitfalls and Solutions

Pitfall 1: Forgetting to Convert Input

# ❌ Wrong - will cause error!
age = input("Enter your age: ")
# This will give error: can't add string and number
next_age = age + 1

# βœ… Correct - convert to int first
age = int(input("Enter your age: "))
next_age = age + 1
print(f"Next year: {next_age}")

Pitfall 2: Type Mismatch in Concatenation

# ❌ Wrong - can't concatenate string and number
score = 95
# print("Your score: " + score)  # Error!

# βœ… Correct solutions:
print("Your score: " + str(score))  # Convert to string
print("Your score:", score)  # Use comma
print(f"Your score: {score}")  # Use f-string (best!)
Your score: 95
Your score: 95
Your score: 95

Pitfall 3: Invalid Input Handling

# ❌ This will crash if user enters non-numeric input
# age = int(input("Enter age: "))  # Crashes if user types "twenty"

# βœ… For now, just be aware users must enter valid data
# Later you'll learn error handling with try/except
print("Note: Make sure to enter valid numbers when prompted!")

2.7 Practice Exercises

Now it’s your turn! Try these exercises:

Exercise 1: Introduction Program

Write a program that asks for the user’s name, age, and favorite food, then prints a friendly message.

# Your code here:
## Ask for name, age, and favorite food
## Print a personalized message using f-strings

Exercise 2: Rectangle Calculator

Create a program that calculates the area and perimeter of a rectangle.

# Your code here:
## Ask user for length and width
## Calculate area (length Γ— width)
## Calculate perimeter (2 Γ— (length + width))
## Print results with 2 decimal places

Exercise 3: Mad Libs Game

Create a simple Mad Libs game that asks for different types of words.

# Your code here:
## Ask user for: adjective, noun, verb, place
## Create a funny story using their inputs
## Print the complete story

Exercise 4: Price Calculator

Create a program that calculates the final price after discount and tax.

# Your code here:
## Ask for original price and discount percentage
## Calculate price after discount
## Add 7% tax
## Display original, discounted, and final prices

2.8 Solutions

Here are the solutions to the exercises:

Solution 1: Introduction Program

Click to show solution
name = input("What is your name? ")
age = int(input("How old are you? "))
food = input("What is your favorite food? ")

print(f"\nNice to meet you, {name}!")
print(f"At {age} years old, you have great taste in food.")
print(f"I love {food} too! It's delicious!")

Solution 2: Rectangle Calculator

Click to show solution
print("=== Rectangle Calculator ===")
length = float(input("Enter length: "))
width = float(input("Enter width: "))

area = length * width
perimeter = 2 * (length + width)

print(f"\nResults:")
print(f"Area: {area:.2f} square units")
print(f"Perimeter: {perimeter:.2f} units")

Solution 3: Mad Libs Game

Click to show solution
print("=== Mad Libs Game ===")
print("I need some words to create a story!\n")

adjective = input("Enter an adjective: ")
noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
place = input("Enter a place: ")

print(f"\n=== YOUR STORY ===")
print(f"Once upon a time, there was a {adjective} {noun}.")
print(f"It loved to {verb} all day long.")
print(f"One day, it went to {place} and lived happily ever after!")

Solution 4: Price Calculator

Click to show solution
print("=== Price Calculator ===")
original_price = float(input("Enter original price: $"))
discount_percent = float(input("Enter discount percentage: "))

# Calculate discounted price
discount_amount = original_price * (discount_percent / 100)
discounted_price = original_price - discount_amount

# Calculate final price with tax
tax = discounted_price * 0.07
final_price = discounted_price + tax

print("\n" + "="*35)
print(f"Original Price:    ${original_price:>10.2f}")
print(f"Discount ({discount_percent}%):    -${discount_amount:>10.2f}")
print(f"Discounted Price:  ${discounted_price:>10.2f}")
print(f"Tax (7%):          +${tax:>10.2f}")
print("-"*35)
print(f"FINAL PRICE:       ${final_price:>10.2f}")
print("="*35)

2.9 Formatting Cheat Sheet

F-String Formatting Quick Reference

value = 123.456789

# Decimal places
print(f"2 decimals: {value:.2f}")

# Width and alignment
print(f"Right aligned: {value:>15.2f}")
print(f"Left aligned: {value:<15.2f}")
print(f"Center aligned: {value:^15.2f}")

# Thousands separator
big_number = 1234567
print(f"With commas: {big_number:,}")

# Percentage
ratio = 0.856
print(f"As percentage: {ratio:.1%}")

# Padding with zeros
number = 42
print(f"Zero padded: {number:05d}")
2 decimals: 123.46
Right aligned:          123.46
Left aligned: 123.46         
Center aligned:     123.46     
With commas: 1,234,567
As percentage: 85.6%
Zero padded: 00042

Common Escape Sequences

print("Escape Sequences:")
print("\\n - New line")
print("\\t - Tab")
print("\\\\ - Backslash")
print("\\\' - Single quote")
print("\\\" - Double quote")
Escape Sequences:
\n - New line
\t - Tab
\\ - Backslash
\' - Single quote
\" - Double quote

2.10 Key Takeaways

✨ Remember:

  1. print() displays information to users
    • Use commas to print multiple items
    • Use sep to customize separators
    • Use end to customize line endings
  2. input() collects user data
    • Always returns a string
    • Convert to int/float for numbers
    • Show clear prompts to users
  3. F-strings are your friend! 🌟
    • Modern and readable: f"Hello {name}"
    • Support formatting: f"{price:.2f}"
    • Can include expressions: f"{x + y}"
  4. Type conversion matters
    • Use int() for whole numbers
    • Use float() for decimals
    • Use str() when concatenating with +
  5. Make output readable
    • Use clear formatting
    • Add spacing and separators
    • Include units and labels

2.11 Next Steps

Now that you understand input and output, you’re ready to learn: - Conditional statements (if/else) - making decisions - Loops (for/while) - repeating actions - Lists and dictionaries - storing collections of data - Functions - organizing reusable code

Keep practicing and happy coding! πŸš€