Why Does This Matter?
Programs that just print the same thing every time are boring. Real programs respond to people. They ask questions, accept answers, and produce personalised results. That conversation between a human and a program is what makes software genuinely useful.
Output is what the program shows you — the messages, results, and information it displays on screen. Input is what you tell the program — your name, your choices, your data. Together, input and output (often shortened to I/O) are how programs communicate with the outside world.
Think about the software you use every day. An ATM asks for your PIN before dispensing cash. A video game asks for your character’s name. A search engine takes your query and returns results. Every one of these is an example of input and output working together.
Real-World Applications of Input & Output
Input and output are not just abstract programming concepts — they power almost every piece of technology you interact with. Here are some real-world examples:
| System | Input (what goes in) | Output (what comes out) |
|---|---|---|
| ATM machine | Card insertion, PIN number, amount requested | Account balance on screen, cash dispensed, printed receipt |
| Search engine | Text query typed into the search box | A ranked list of relevant web pages and snippets |
| Voice assistant (e.g. Siri, Alexa) | Spoken words captured by a microphone | Spoken response, on-screen answer, or an action (e.g. setting a timer) |
| Medical system | Patient data: symptoms, test results, medical history | Diagnosis suggestions, recommended treatments, alerts for doctors |
In every case, the pattern is the same: data goes in, the system processes it, and a result comes out. Learning to handle input and output in Python gives you the foundation to build any of these kinds of systems.
By the end of this chapter, you will be able to:
- Use
print()with different formatting techniques to produce clear, readable output - Use f-strings (formatted string literals) to combine variables and text elegantly
- Join strings together using concatenation with the
+operator - Understand how
input()works in Python to collect data from users - Control print formatting with the
sepandendparameters - Use escape characters to include special characters in your strings
- Format strings using the older
.format()method - Combine input, arithmetic, and formatted output to build useful programs
See It in Action
Example 1: Print Formatting with f-strings
An f-string (formatted string literal) lets you embed variables directly inside a string. Just put an f before the opening quote, and wrap any variable name in curly braces {}. Python fills in the values for you.
print() statements below. The third one contains {age + 1} inside the f-string. What will the third line print — will Python do the maths inside the curly braces, or will it print the text literally?
I attend Greenwood Academy.
Next year I will be 16!
# f-strings: the modern way to format output
name = "Alice"
age = 15
school = "Greenwood Academy"
print(f"My name is {name} and I am {age} years old.")
print(f"I attend {school}.")
print(f"Next year I will be {age + 1}!")
name, age, and school to your own details and run the code again. Notice how the output updates automatically because f-strings pull the current value of each variable.
Example 2: String Concatenation
Before f-strings existed, programmers joined strings together using the + operator. This is called concatenation (from the Latin word meaning “to chain together”). It still works perfectly and you will see it in lots of existing code.
first_name + " " + surname runs, what will full_name contain? Why is the " " in the middle important — what would happen without it?
Hello, Priya Sharma! Welcome to Python.
Without the " ", full_name would be "PriyaSharma" — no space between the names!
# String concatenation: joining strings with +
first_name = "Priya"
surname = "Sharma"
# Joining strings together
full_name = first_name + " " + surname
print("Full name: " + full_name)
# You can build up longer messages
greeting = "Hello, " + full_name + "! "
greeting = greeting + "Welcome to Python."
print(greeting)
nickname. Concatenate it into the greeting so it says something like “Hello, Priya Sharma! Your friends call you Pri.”
Example 3: Simulating User Input
In a standard Python environment, the input() function pauses the program and waits for the user to type something. Since we are running Python in the browser, we cannot use input() directly. Instead, we will pre-set variables to simulate what a user might type. The important thing is to understand the concept — you will use real input() when you run Python on your own computer.
# In a real Python program, you would write:
# name = input("What is your name? ")
# colour = input("What is your favourite colour? ")
# But since we're running in the browser, we set values directly:
name = "Jordan" # Try changing this to your name!
colour = "turquoise" # Try changing this to your favourite colour!
# Now we use the variables just as if the user had typed them
print(f"Hello, {name}!")
print(f"Ah, {colour} is a lovely colour.")
print(f"Here's a fun fact, {name}: Python was named after Monty Python!")
name and colour at the top to your own choices. Add a third variable — perhaps hobby — and include it in one of the print statements.
Example 4: Escape Characters & Special Characters
Sometimes you need to include characters in a string that are difficult to type directly — a new line, a tab, or even a quotation mark. Python uses the backslash (\) as an escape character to signal that the next character has a special meaning.
# \n creates a new line inside a string
print("Line one\nLine two\nLine three")
print() # blank line to separate examples
# \t inserts a tab (useful for aligning columns)
print("Name\tAge\tCity")
print("Alice\t15\tLondon")
print("Ben\t14\tManchester")
print()
# \\ prints a literal backslash
print("The file is at C:\\Users\\student\\homework.py")
# \" lets you include double quotes inside a double-quoted string
print("She said, \"Python is brilliant!\"")
# Alternatively, mix quote types to avoid escaping
print('She said, "Python is brilliant!"')
\t to align the data. Try printing a Windows file path using \\. What happens if you forget one of the backslashes?
Example 5: String Formatting with .format()
Before f-strings were introduced, Python programmers used the .format() method. You will still see this in plenty of existing code, tutorials, and textbooks, so it is worth understanding how it works. Instead of putting an f before the string, you place empty curly braces {} as placeholders and then call .format() at the end, passing in the values.
# The .format() method — the older way to format strings
name = "Marcus"
age = 16
subject = "Computer Science"
# Positional placeholders (filled in order)
print("Hello, {}! You are {} years old.".format(name, age))
# Numbered placeholders (you choose the order)
print("{0} studies {1}. {0} is {2}.".format(name, subject, age))
# Named placeholders (most readable version)
print("Student: {n}, Subject: {s}".format(n=name, s=subject))
# Formatting numbers with .format()
price = 19.5
print("The total is £{:.2f}".format(price))
.format() examples above using f-strings instead. Which version do you find easier to read? Most Python programmers today prefer f-strings, but knowing .format() means you can read older code confidently.
Example 6: Building a Simple Calculator
Let’s combine what we have learnt — variables, type conversion, arithmetic, and formatted output — to build a working calculator. In a real program, the numbers would come from input(); here we pre-set them.
# Simple calculator — simulating user input
# In real Python: num1 = float(input("Enter first number: "))
num1 = 24.5
num2 = 7
# Perform all four basic operations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
# Display results with neat formatting
print("=" * 30)
print(" SIMPLE CALCULATOR")
print("=" * 30)
print(f" First number: {num1}")
print(f" Second number: {num2}")
print("-" * 30)
print(f" Addition: {addition}")
print(f" Subtraction: {subtraction}")
print(f" Multiplication: {multiplication}")
print(f" Division: {division:.2f}")
print("=" * 30)
num1 and num2 to different values and run the code again. Can you add a fifth operation — perhaps the modulus (%) which gives the remainder after division, or integer division (//)?
How Does It Work?
The print() Function in Detail
You have been using print() since Chapter 1, but it can do much more than you might think. It accepts multiple arguments separated by commas, and has special parameters to control how the output looks.
# Multiple arguments - print() adds a space between each one
print("Name:", "Alice", "Age:", 15)
# The sep parameter changes what goes between arguments
print("09", "05", "2010", sep="/") # Date format
print("alice", "example", "com", sep="@") # Looks like an email (almost!)
print("Python", "is", "fun", sep=" --- ")
# The end parameter changes what goes at the very end
# Normally print() adds a newline (\n) at the end
print("Loading", end="")
print("...", end="")
print(" Done!")
By default, print() separates each argument with a space (that is, sep=" ") and ends with a new line (that is, end="\n"). Changing these parameters gives you fine control over your output.
print was a statement, not a function. You could write print "Hello" without any brackets! In Python 3 (the version you are learning), the brackets are required: print("Hello"). If you ever see Python code without brackets around print, you know it was written for the older version.
f-strings (Formatted String Literals)
f-strings were introduced in Python 3.6 and are now the preferred way to combine variables and text. The f before the quote tells Python to look inside the string for curly braces and replace them with the value of whatever expression is inside.
# f-strings can contain any Python expression
item = "notebook"
price = 2.50
quantity = 3
# Simple variable insertion
print(f"Item: {item}")
# Arithmetic inside the braces
print(f"Total cost: £{price * quantity}")
# Formatting numbers - .2f means 2 decimal places
total = price * quantity
print(f"Total cost (formatted): £{total:.2f}")
# You can even call string methods inside f-strings
print(f"Item (uppercase): {item.upper()}")
print(f"Item (capitalised): {item.capitalize()}")
.format() or the even older % operator for string formatting. f-strings quickly became the favourite because they are easier to read and faster for Python to process.
f before the opening quotation mark, then put any variable or expression inside curly braces: f"Hello, {name}!". You can even do calculations and call methods inside the braces.
String Concatenation with +
Concatenation is straightforward: use the + operator to join two strings together. However, there is an important catch — you can only concatenate strings with other strings. If you try to join a string and a number, Python will raise a TypeError.
# Concatenation works with strings
word1 = "fire"
word2 = "fly"
print(word1 + word2) # firefly
# But numbers must be converted to strings first!
score = 42
# This would cause an error: print("Score: " + score)
# Instead, use str() to convert the number:
print("Score: " + str(score))
# f-strings handle this automatically (another reason to prefer them!)
print(f"Score: {score}")
+. For example, "Age: " + 15 will crash with a TypeError. You must convert the number first with str(15), or better yet, use an f-string: f"Age: {15}".
The Concept of input()
In a real Python environment (such as IDLE, VS Code, or the terminal), the input() function is how your program asks the user a question and waits for their response. Here is how it works:
# How input() works in a real Python environment:
#
# name = input("What is your name? ")
# age = input("How old are you? ")
#
# The program would pause at each line and wait for the user to type.
# Whatever the user types is stored as a STRING in the variable.
#
# IMPORTANT: input() ALWAYS returns a string!
# So if the user types 15, age would be the string "15", not the number 15.
# To use it as a number, you must convert it: age = int(age)
# Let's simulate this in the browser:
name = "Sam" # Simulates: name = input("What is your name? ")
age = "14" # Simulates: age = input("How old are you? ")
# Convert age from a string to an integer
age = int(age)
print(f"Hello, {name}!")
print(f"You are {age} years old.")
print(f"In 10 years you will be {age + 10}.")
input() function always returns a string, even if the user types a number. If you need to do maths with the input, you must convert it using int() for whole numbers or float() for decimal numbers. For example: age = int(input("How old are you? ")).
print() function gets its name from those early days when output was literally printed on paper.
Escape Characters Reference
Here is a quick reference for the most common escape characters you will use in Python:
| Escape Sequence | What It Does | Example Output |
|---|---|---|
\n |
Starts a new line | Line 1 Line 2 |
\t |
Inserts a horizontal tab | Name Age |
\\ |
Prints a literal backslash | C:\Users\ |
\" |
Prints a double quote inside a double-quoted string | He said "hello" |
\' |
Prints a single quote inside a single-quoted string | It's great |
Comparing the Three Approaches
Here is a quick summary of the three main ways to build output strings:
| Method | Example | Notes |
|---|---|---|
| f-string | f"Hello, {name}!" |
Modern, clean, handles numbers automatically. Recommended. |
| Concatenation | "Hello, " + name + "!" |
Simple but needs str() for numbers. Can get messy with many variables. |
| .format() | "Hello, {}!".format(name) |
Older method. Still common in existing code. Handles numbers automatically. |
| Multiple arguments | print("Hello,", name) |
Easy but adds spaces automatically. Less control over formatting. |
Common Mistakes
Here are the most frequent errors students make with input and output. Knowing these in advance will save you a lot of debugging time!
f prefix:
Writing print("{name}") without the f will literally print {name} instead of the variable’s value. You must write print(f"{name}"). It is an easy mistake to make and can be tricky to spot!
{ needs a matching closing brace }. Writing print(f"Hello {name") will cause a SyntaxError. Always double-check that your braces and parentheses are balanced.
print("The answer is " + 42) will crash with a TypeError because you cannot join a string and an integer with +. Fix it with str(42) or use an f-string: f"The answer is {42}".
print('it's a lovely day') will cause a SyntaxError because the apostrophe in “it’s” ends the string early. Fix it by using double quotes on the outside: print("it's a lovely day"), or escape the apostrophe: print('it\'s a lovely day').
Key Vocabulary
Make sure you understand these terms — they will come up in lessons, homework, and exams.
| Term | Definition |
|---|---|
| Output | Data that a program sends out to the user, such as text displayed on screen. In Python, print() is the main output function. |
| Input | Data that a user provides to a program. In Python, input() pauses the program and waits for the user to type something. |
| f-string | A formatted string literal. A string prefixed with f that allows you to embed expressions inside curly braces, e.g. f"Hello, {name}". |
| Concatenation | Joining two or more strings together using the + operator, e.g. "Hello" + " " + "World". |
| String Formatting | The process of inserting variable values into a string template. Can be done with f-strings, .format(), or concatenation. |
| Escape Character | A backslash (\) followed by a character that has a special meaning, e.g. \n for a new line or \t for a tab. |
| Type Casting | Converting a value from one data type to another, e.g. int("15") converts the string "15" to the integer 15. |
| Argument | A value passed into a function when you call it. In print("Hello"), the string "Hello" is the argument. |
| Parameter | A named option in a function definition that receives an argument. In print(), sep and end are parameters. |
| sep | A parameter of print() that controls the separator between multiple arguments. Default is a space (" "). |
| end | A parameter of print() that controls what is printed at the very end. Default is a newline character ("\n"). |
| Newline Character | The special character \n that moves the cursor to the start of the next line. print() adds one automatically at the end of each call. |
Worked Example: Building a BMI Calculator
Let’s walk through a complete worked example that brings together variables, arithmetic, formatted output, and even a simple if statement (a sneak peek at Chapter 4!). We will build a Body Mass Index (BMI) calculator.
BMI is calculated using the formula:
BMI = weight (kg) ÷ height (m)²
Step 1: Set up the variables
In a real program, these would come from input(). Here we pre-set them to simulate user data.
Step 2: Calculate the BMI
We use the formula above. The ** operator raises a number to a power, so height ** 2 means “height squared”.
Step 3: Format and display the result
We use :.1f in the f-string to display the BMI to one decimal place.
Step 4: Classify the result
We add if/elif/else statements to give the user a classification based on their BMI value.
# === BMI Calculator ===
# In real Python:
# weight = float(input("Enter your weight in kg: "))
# height = float(input("Enter your height in metres: "))
weight = 65.0 # kilograms — try changing this!
height = 1.72 # metres — try changing this!
# Step 2: Calculate BMI
bmi = weight / (height ** 2)
# Step 3: Display formatted result
print("=" * 32)
print(" BMI CALCULATOR")
print("=" * 32)
print(f" Weight: {weight} kg")
print(f" Height: {height} m")
print("-" * 32)
print(f" Your BMI is: {bmi:.1f}")
print("-" * 32)
# Step 4: Classify the result
if bmi < 18.5:
category = "underweight"
elif bmi < 25:
category = "healthy weight"
elif bmi < 30:
category = "overweight"
else:
category = "obese"
print(f" Category: {category}")
print("=" * 32)
print()
print("Note: BMI is a rough guide only")
print("and does not account for muscle,")
print("age, or other important factors.")
weight and height values to see how the BMI and category change. Can you add an extra elif to split the “healthy weight” range into two sub-categories? What about adding a line that shows the BMI to 2 decimal places as well?
Your Turn
Create variables to store your name, age, and favourite subject. Then use f-strings to print three sentences that introduce yourself.
my_name and store your name in itSTEP 2: Create a variable called
my_age and store your age as a numberSTEP 3: Create a variable called
fav_subject and store your favourite subjectSTEP 4: Use
print() with f-strings to display: “Hi, I’m [name]!”STEP 5: Print: “I am [age] years old and my favourite subject is [subject].”
STEP 6: Print: “In 5 years I will be [age + 5] years old.”
# Exercise 1: All About Me
# Fill in the variables with your own details
my_name = "____"
my_age = ____
fav_subject = "____"
# Now use f-strings to print three sentences
print(f"Hi, I'm ____!")
print(f"____")
print(f"____")
f"My name is {my_name}". For the last line, you can do arithmetic inside the braces: {my_age + 5}.Mad Libs is a word game where you fill in blanks to create a funny story. Create variables for different types of words, then use them to build a short silly paragraph. In a full Python program, these words would come from input() — here, we pre-set them.
STEP 2: Use f-strings to print a silly story that uses all five variables
STEP 3: The story should be at least three sentences long
STEP 4: Print a blank line between the title and the story (use an empty
print())
# Exercise 2: Mad Libs Story
# In real Python you'd use input() for each word:
# animal = input("Enter an animal: ")
# Here, set them directly:
animal = "penguin"
adjective = "sparkly"
verb = "danced"
place = "the moon"
number = 47
print("=== My Mad Libs Story ===")
print()
# Write your story below using f-strings!
print(f"One day, a {adjective} {animal} {verb} all the way to {place}."). Try to use each variable at least once. You can use {number} for a quantity in the story. The sillier the variable values, the funnier the result!Create a program that displays a neatly formatted shop receipt or school report card. Use variables for the items/subjects and their prices/grades. Your output should look professional with aligned text, a title, and a total or average at the bottom.
# Exercise 3: Formatted Receipt or Report Card
# Create a professional-looking display using print() and f-strings.
#
# Option A - Shop Receipt:
# Create variables for at least 3 items with prices.
# Display them neatly with a total at the bottom.
#
# Option B - Report Card:
# Create variables for at least 4 subjects with grades/percentages.
# Display them neatly with an average at the bottom.
#
# Tip: Use string multiplication for lines, e.g. print("=" * 30)
# Example start (feel free to replace entirely):
shop_name = "Python Corner Shop"
print("=" * 34)
print(f" {shop_name}")
print("=" * 34)
# Add your items and totals below!
For a receipt, try something like this structure:
item1 = "Banana" and price1 = 0.30
Then print each line: print(f"{item1}............£{price1:.2f}")
The :.2f format specifier ensures prices always show two decimal places (e.g. £0.30 not £0.3).
For neat columns, try padding: f"{'Banana':<20}£{0.30:>6.2f}" — the <20 left-aligns in 20 characters and >6 right-aligns in 6 characters.
Create a formatted multiplication quiz that displays questions and their answers in a neat, aligned table. Use f-strings with alignment specifiers to make everything line up properly. This is excellent practice for formatting output — a skill that will come up again and again in your programming journey.
STEP 2: Print a title line with the table number
STEP 3: Print a separator line using string multiplication
STEP 4: Use a loop or individual print statements to show each multiplication from 1 to 12
STEP 5: Use f-string alignment (e.g.
{value:>4}) to right-align the numbersSTEP 6: Add a footer separator line
# Exercise 4: Maths Quiz Display
# Create a neatly formatted times table
table_number = 7 # Change this to any number!
print(f"=== {table_number} Times Table ===")
print("-" * 24)
# Hint: {value:>4} right-aligns a number in 4 character spaces
# Example for first three rows (complete the rest!):
print(f" {table_number} x 1 = {table_number * 1:>4}")
print(f" {table_number} x 2 = {table_number * 2:>4}")
print(f" {table_number} x 3 = {table_number * 3:>4}")
# Add rows for 4 through 12 below!
print("-" * 24)
Continue the pattern for each row up to 12. For example:
print(f" {table_number} x 4 = {table_number * 4:>4}")
For numbers 10, 11, 12, you will need to adjust the spacing so the numbers still line up. The :>4 format specifier right-aligns the answer in a space 4 characters wide, which keeps the columns neat.
Bonus challenge: If you already know about loops (Chapter 5), try replacing all the individual print statements with a single for loop!
Create a Mad Libs style story generator with at least 8 different variables. In a real Python program, each variable would come from an input() call. Here, pre-set each value, then weave them all into a multi-paragraph story. Be creative — the funnier the story, the better!
# Exercise 5: Interactive Story Generator
# Create a Mad Libs story with at least 8 variables.
# In real Python, each would use input():
# character = input("Enter a character name: ")
# adjective1 = input("Enter an adjective: ")
# Here, set them directly:
character = "Captain Socks"
adjective1 = "magnificent"
adjective2 = "tiny"
animal = "flamingo"
food = "spaghetti"
place = "the Sahara Desert"
number = 1000
verb_past = "somersaulted"
# Write your story below!
# Requirements:
# - Use ALL 8 variables at least once
# - At least 3 paragraphs (use print() for blank lines between them)
# - Include a title
# - Use f-strings throughout
# - Bonus: use \n or \t for extra formatting
print("=" * 40)
print(" THE ADVENTURES OF ????")
print("=" * 40)
print()
# Your story goes here...
Build your story paragraph by paragraph. Here is a possible opening:
print(f"Once upon a time, {character} woke up in {place}.")
print(f"Beside them stood a {adjective1} {animal} eating {food}.")
Remember to use print() on its own to create blank lines between paragraphs. Try to make the story flow naturally while including all the variables. The more variables you add beyond the minimum of 8, the more unpredictable and entertaining the story becomes!
Chapter Summary
Here is a recap of everything you have learnt in this chapter:
- Output is how your program communicates results to the user. The
print()function is the primary way to produce output in Python. - Input is how the user provides data to your program. The
input()function always returns a string, so you must convert it withint()orfloat()if you need a number. - f-strings (e.g.
f"Hello, {name}!") are the modern, preferred way to combine variables and text. Place anfbefore the opening quote and put expressions inside{}. - Concatenation uses the
+operator to join strings. You must convert numbers to strings withstr()before concatenating. - The
.format()method is an older string formatting approach you may see in existing code. - Escape characters like
\n(new line),\t(tab), and\\(backslash) let you include special characters in strings. - The
sepandendparameters ofprint()give you fine control over spacing and line endings. - Number formatting in f-strings (e.g.
{price:.2f}) lets you control decimal places and alignment.
Exam-Style Questions
Test your understanding with these exam-style questions. Try answering them on paper before checking the hints for guidance.
What data type does the input() function always return?
The input() function always returns a string (str), regardless of what the user types. Even if the user types 42, the result is the string "42", not the integer 42. To use the value as a number, you must convert it with int() or float().
Explain what an f-string is and give an example of how it is used.
1 mark: An f-string (formatted string literal) is a string that has an f placed before the opening quotation mark.
1 mark: It allows you to embed variables or expressions directly inside the string by placing them in curly braces {}.
1 mark: Example: name = "Alice" followed by print(f"Hello, {name}!") would output Hello, Alice!
A student writes the following code:
print("The answer is " + 42)
Explain the error this code will produce and give two different ways to fix it.
1 mark for identifying the error: This code will cause a TypeError because you cannot concatenate (join with +) a string and an integer. The + operator requires both values to be the same type.
1 mark for fix 1: Convert the integer to a string using str(): print("The answer is " + str(42))
1 mark for fix 2: Use an f-string, which handles type conversion automatically: print(f"The answer is {42}")
Think About It
- Why do you think
input()always returns a string, even when the user types a number? What problems could this cause if you are not careful? - When would you choose concatenation (
+) over an f-string? Can you think of a situation where one is clearly better than the other? - Think about a program you use every day (a game, an app, a website). What kinds of input does it accept, and what kinds of output does it produce?
- Why is formatting important? Imagine a receipt where all the numbers are misaligned, or a report with no headings. How would that affect the user?
- The
.format()method and f-strings both achieve the same thing. Why do you think Python added f-strings if.format()already worked? What advantages do f-strings offer?
Interactive Activities
- Python I/O Challenges — 5 interactive challenges practising input, type conversion and output with a live Python editor
Extra Resources
Practise your input and output skills further with these resources:
- GCSE Topic 6: Programming — Interactive code editors covering
input(),print(), and type casting - Python Code Fixer — Find and fix bugs in real Python programs
- BBC Bitesize Edexcel Computer Science — Comprehensive GCSE revision covering programming fundamentals
- W3Schools: Python String Formatting — Interactive examples and exercises on f-strings and
.format() - W3Schools: Python User Input — Clear guide to the
input()function with examples - Real Python: f-strings Guide — In-depth tutorial on f-strings with advanced formatting tips
What’s Next?
So far, your programs run every line from top to bottom, every single time. But what if you want your program to make decisions? What if it should say “well done” for a high score but “try again” for a low one? In Chapter 4: If Statements, you will learn how to give your programs the power of choice — making them respond differently depending on the situation. Get ready to make your programs truly intelligent!