MGU Computer Science Series — Programming with Python
Part I: Getting Started with Python
print() · input() · Type Conversion · f-Strings · Testing
Chapter 4 of 30
4
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Chapter 4:
Input, Output, and
Simple Programs

How programs speak and listen — displaying results, receiving user input, converting types, formatting output with f-strings, and building your first complete interactive programs

■ Part I of VII  ·  Getting Started with Python ■

■ 10 Sections  •  Chapter 4 of 30 ■

Prerequisite: Chapters 1–3 — values, variables, expressions, and arithmetic

Chapter Introduction and Learning Objectives

Every program you have written so far has been a one-way conversation. The program runs. It does something. It finishes. But most useful programs are interactive. They ask questions. They receive answers. They do something with what they receive and report a result back.

This chapter teaches you how to make programs interactive. You will learn how to display results in a variety of useful forms, how to receive information from a user while a program runs, how to convert that information into a type your program can work with, and how to combine everything into small but complete programs.

By the end of this chapter, you will be able to build programs that greet users by name, perform calculations from values the user supplies, convert units, and produce clear, formatted output. These are genuinely useful programs, not just exercises.

The ideas in this chapter sit at the heart of almost every Python program you will write. Reading them carefully and practicing each skill before moving on will pay off in every chapter that follows.

Where This Chapter Fits

Chapters 1 through 3 taught you Python's basic ingredients: how to run programs, how values and variables work, and how expressions are evaluated. Those tools let you build programs that calculate — but only with values written directly into the code.

This chapter adds two essential capabilities: output (displaying results in a controlled, readable form) and input (receiving values from the person running the program). Together, they complete the foundation of interactive programming. Every chapter from 5 onward assumes you can read input, process it, and display results clearly.

10Sections
12Objectives
18Key Terms
30Total Chapters

Learning Objectives

By the end of this chapter, you should be able to:

  1. 1Use print() to display strings, numbers, variables, and computed expressions.
  2. 2Explain the difference between displaying multiple values with commas versus string concatenation.
  3. 3Write comments that explain purpose, not just syntax, and use blank lines to organize code visually.
  4. 4Use input() with a clear prompt to receive text from a user and store it in a variable.
  5. 5Explain why input() always returns a string, even when the user types a number.
  6. 6Use int(), float(), and str() to convert values between types.
  7. 7Combine input() and a conversion function in a single statement using the standard Python idiom.
  8. 8Write f-strings that embed variables, expressions, and format specifiers.
  9. 9Use the :.2f format specifier to display floats with a controlled number of decimal places.
  10. 10Plan and build a short interactive program using the input-process-output pattern.
  11. 11Design and run test cases for a simple program, including typical values, boundary values, and edge cases.
  12. 12Read a Python error message, identify the error type, and locate the line where the problem occurred.

Sections at a Glance

Sections 4.1 – 4.3
Displaying Information and Organizing Code
print() · Values · Comments · Readable Style

Output with print()

Displaying Information

When a Python program wants to show something to the user, it uses the print() function. You have already seen print() in earlier chapters. Now it is time to understand it more completely.

The simplest use of print() passes a single value inside the parentheses:

print("Hello, world!")
print(42)
print(3.14)
Hello, world!
42
3.14

Each call to print() displays its value and then moves to a new line. That automatic new line is the default behavior. After print("Hello, world!") runs, the cursor moves down one line so the next output starts fresh below it.

Printing Multiple Values at Once

You can pass more than one value to print() by separating them with commas:

print("The answer is", 42)
print("Temperature:", 98.6, "degrees")
The answer is 42
Temperature: 98.6 degrees

When you separate values with commas inside print(), Python automatically places a single space between them. This is useful for combining labels and values in a readable way.

Printing Nothing

Calling print() with nothing inside produces a blank line. This is sometimes useful for spacing your output:

print("First section")
print()
print("Second section")
First section

Second section

The end Parameter

By default, print() adds a newline character at the end of its output. You can change this using the end parameter:

print("Loading", end="")
print("...")
Loading...

The two print calls produce output on the same line because the first one ends with an empty string instead of a newline. You will not need end often in early programs, but knowing it exists explains why output sometimes behaves unexpectedly.

The sep Parameter

You can also control what goes between values using the sep parameter:

print("2025", "06", "15", sep="-")
2025-06-15
Study Note

You will not use end or sep constantly. However, understanding them helps you read other people's code and explains surprising output when you encounter them. Knowing a feature exists is different from needing to use it immediately.

Text, Numbers, and Displayed Results

What print() Can Display

print() is remarkably flexible. It can display strings, integers, floats, Booleans, and many other kinds of values. Python converts each value to a displayable form automatically.

print("Name:", "Jordan")
print("Age:", 17)
print("GPA:", 3.85)
print("Enrolled:", True)
Name: Jordan
Age: 17
GPA: 3.85
Enrolled: True

Displaying Computed Results

You can pass an expression directly to print(). Python evaluates the expression first, then displays the result:

print(10 + 5)
print(100 / 4)
print(2 ** 8)
15
25.0
256
Division Always Returns a Float

Notice that 100 / 4 produces 25.0, not 25. In Python, the / operator always returns a float, even when the result is a whole number. If you want an integer result, use // (floor division):

print(100 // 4)   # floor division: integer result
print(7 // 2)     # 3, not 3.5
25
3

Displaying Variables

Displaying a variable shows its current value. The variable name itself does not appear in the output — only its value does:

score = 88
name = "Priya"
print(name)
print(score)
print("Score for", name, ":", score)
Priya
88
Score for Priya : 88
Notice the Extra Space

Python places spaces between values passed with commas. The space before the colon in Score for Priya : 88 comes from that automatic spacing. Section 4.8 covers f-strings, which give you precise control over spacing and formatting without this awkwardness.

Comments and Readable Code

What Comments Are

A comment is a note written in source code for humans to read. Python ignores comments entirely when it runs a program. Comments do not affect what a program does. They explain what the program is doing, why certain choices were made, or how a section of code works.

In Python, a comment begins with a hash symbol (#). Everything from the # to the end of the line is the comment:

# This program greets the user
print("Hello, welcome to the program.")

Comments can appear on their own line or at the end of a line of code:

price = 9.99       # price in dollars
tax_rate = 0.08    # 8 percent tax

Why Comments Matter

Beginners sometimes skip comments because the code seems obvious when they write it. But code that seems obvious today often becomes confusing later — even to the person who wrote it. Comments are also essential when other people read your programs.

Good comments explain why, not just what. Avoid comments that simply restate what the code already says clearly:

# Avoid this — it just restates the code
x = x + 1    # add 1 to x

# Better — it explains the purpose
attempts = attempts + 1    # count this as one failed login attempt

When to Use Comments

Do Comment
Purpose and Reasoning
Explain the overall purpose of a program or section. Clarify a calculation that might not be obvious. Explain why an unusual approach was taken. Label sections of a longer program.
Avoid Commenting
Obvious Code
Do not explain every single line of simple code. Do not leave large blocks of old, unused code without explanation. Do not use comments to compensate for confusing variable names — fix the names instead.

Blank Lines as Visual Organization

Blank lines do not affect program behavior, but they make code easier to read by grouping related lines together. Use a blank line to separate logical sections:

# Get user input
name = input("What is your name? ")
age = input("What is your age? ")

# Display a greeting
print("Hello,", name)
print("You are", age, "years old.")

This visual separation helps a reader understand that the program has two distinct phases: gathering information, then displaying it. You will see this kind of organization in every program in this chapter.

Sections 4.4 – 4.6
Receiving Information from the User
input() · Prompts · Strings · Concatenation

Input with input()

Programs That Ask Questions

The input() function pauses a program, displays a message to the user, waits for the user to type something and press Enter, and then returns whatever the user typed as a string.

name = input("What is your name? ")
print("Hello,", name)

When this program runs, it displays a prompt and waits. If the user types Marcus and presses Enter, the string "Marcus" is stored in name. Then print() displays:

Hello, Marcus

How input() Works — Step by Step

Execution Flow
Tracing a single input() call
  • Step 1Python calls input() with the prompt string "What is your name? ".
  • Step 2Python displays the prompt to the user.
  • Step 3The program pauses. Execution stops here until the user acts.
  • Step 4The user types something and presses Enter.
  • Step 5input() returns everything the user typed, as a string.
  • Step 6The assignment operator stores that string in the variable name.
  • Step 7The program continues with the next line.
The Most Important Fact About input()

input() always returns a string, no matter what the user types. If the user types 42, the variable holds the string "42", not the integer 42. This has important consequences. Section 4.7 explains how to convert these strings to numbers before doing arithmetic.

The Prompt Argument

The string inside input() is the prompt. Good prompts are clear and end with a space or colon-space so there is room between the prompt and the user's cursor. Without a trailing space, the display looks cramped:

# Without a trailing space — cramped
city = input("Enter your city:")

# With a trailing space — clean
city = input("Enter your city: ")
Always Provide a Prompt

You can call input() without any argument, but this leaves the user staring at a blank cursor with no explanation. Always provide a prompt that tells the user exactly what to type. An unclear or missing prompt is one of the most common sources of user confusion in early programs.

Prompts and User Interaction

Designing Prompts Thoughtfully

A prompt is an instruction to the user. It should tell the user exactly what to type. Unclear prompts cause confusion and lead to programs that receive unexpected input.

Vague PromptClear PromptWhat Improved
input("Enter: ")input("Enter the temperature in Celsius: ")Specifies what kind of value and what unit
input("Number? ")input("Enter tip percentage (e.g. 18 for 18%): ")Gives an example so format is clear
input("Date: ")input("Enter birth year (e.g. 2008): ")Specifies expected format with an example

Asking Multiple Questions

Programs often need several pieces of input. Each call to input() pauses the program and waits for a response:

first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
age = input("Enter your age: ")

print("Full name:", first_name, last_name)
print("Age:", age)

The program asks three questions in sequence. Each answer is stored in its own variable. Notice that age is still a string at this point — section 4.7 covers how to convert it to a number.

The Input-Process-Output Structure

A common pattern in early programs is to gather all input first, then perform calculations, then display output. This keeps the program organized and makes each phase easy to find:

# Phase 1: gather input
length = input("Enter the length in feet: ")
width = input("Enter the width in feet: ")

# Phase 2: calculate
area = float(length) * float(width)

# Phase 3: display output
print("Area:", area, "square feet")
A Pattern Worth Remembering

The input-process-output structure appears in programs of all sizes — from a two-line script to a large application. Organizing your thinking around these three phases helps you plan before you code, identify where a bug is likely to live, and explain your program to others. Section 4.9 applies this pattern to several complete worked examples.

Strings from Input

Everything from input() Is a String

When a user types something and presses Enter, input() gives your program a string. Even if the user typed a number, Python gives you the string form of that number.

response = input("Enter a number: ")
print(type(response))

If the user types 10, the output is:

<class 'str'>

The value stored in response is "10" — a string containing two characters, the digit 1 and the digit 0 — not the integer 10.

Why This Matters

Trying to do arithmetic with a string causes an error:

age = input("Enter your age: ")
next_year = age + 1   # This will fail
TypeError: can only concatenate str (not "int") to "str"

Python cannot add an integer to a string. Before doing arithmetic, you must convert the string to a number. That is what section 4.7 covers.

String Concatenation with Input Results

One thing you can do with string input right away is join it with other strings. The + operator joins two strings together. This is called string concatenation:

name = input("What is your name? ")
greeting = "Hello, " + name + "!"
print(greeting)

If the user types Sofia, the output is:

Hello, Sofia!

Notice that "Hello, " includes a space after the comma, and "!" has no space before it. String concatenation joins strings exactly as written, with no automatic spacing.

Concatenation Versus Comma-Separated Printing

These two lines produce identical output:

print("Hello, " + name + "!")
print("Hello,", name + "!")

But they are different mechanisms. The first uses string concatenation to build a single string before printing. The second passes two values to print(), relying on automatic spacing. For tight control over formatting, string concatenation or f-strings (section 4.8) are usually better.

Trace Before You Run

When you are unsure what a print() statement will produce, trace it on paper. Evaluate each part of the expression, then combine them. This habit builds the mental model you need to debug programs without running them first.

Sections 4.7 – 4.8
Working with Types and Formatting Output
Type Conversion · int() · float() · str() · f-Strings · Format Specifiers

Type Conversion

Converting Between Types

Python provides built-in functions for converting values from one type to another. The three most important for this chapter are:

Function
int()
Converts a value to an integer. Works on numeric strings like "42" and on floats (truncates — does not round). Fails on non-numeric strings.
Function
float()
Converts a value to a floating-point number. Works on integer strings like "100" and on decimal strings like "3.14". More flexible than int() for user input.
Function
str()
Converts a value to a string. Works on integers, floats, Booleans, and almost anything else. Essential when building output with string concatenation.

Converting Strings to Numbers

When you receive a number from input(), it arrives as a string. Before performing arithmetic, convert it:

age_string = input("Enter your age: ")
age = int(age_string)
next_birthday = age + 1
print("Next year you will be", next_birthday)

If the user types 16:

Next year you will be 17

A more compact version combines the input() call and the conversion in a single line:

age = int(input("Enter your age: "))
A Standard Python Idiom

The combined form age = int(input("Enter your age: ")) is idiomatic Python — the standard way programmers write input followed by conversion. input() runs first and returns a string. int() immediately converts that string to an integer. The result is stored in age. You will see this pattern constantly. Learn to read it fluently before writing it.

Using float() for Decimal Input

When the user might enter a decimal value, use float() instead of int():

temperature = float(input("Enter the temperature in Celsius: "))
fahrenheit = temperature * 9 / 5 + 32
print("In Fahrenheit:", fahrenheit)

If the user types 100:

In Fahrenheit: 212.0
Choose float() When Input May Contain Decimals

float() can convert both integer-looking strings like "100" and decimal strings like "36.6". int() cannot convert "36.6" — it raises a ValueError. Whenever the user might enter a decimal value, use float().

Converting Numbers to Strings

Sometimes you need to convert a number to a string, particularly when building output with string concatenation:

score = 95
message = "Your score is " + str(score) + " out of 100."
print(message)
Your score is 95 out of 100.

Without str(score), the + operator would raise a TypeError because you cannot concatenate a string and an integer directly.

What Happens When Conversion Fails

Type conversion is not always possible. If the user types "hello" when your program calls int(input(...)), Python raises a ValueError:

ValueError: invalid literal for int() with base 10: 'hello'

This is a runtime error — the program stops mid-execution. For now, you can assume that users will type what you ask for. Chapter 23 covers exception handling, which lets programs respond gracefully to bad input instead of crashing.

Conversion Reference

ExpressionResultNotes
int("42")42String to integer
int(3.9)3Float to integer — truncates, does not round
int(-2.7)-2Truncation moves toward zero
float("3.14")3.14String to float
float(7)7.0Integer to float
str(100)"100"Integer to string
str(3.14)"3.14"Float to string
str(True)"True"Boolean to string
Truncation Is Not Rounding

Converting a float to an integer with int() truncates — it drops everything after the decimal point. int(3.9) produces 3, not 4. If you need rounding, use the built-in round() function: round(3.9) returns 4.

Formatted Output with f-Strings

The Problem with Concatenation and Commas

String concatenation and comma-separated print() calls work, but they can become awkward as programs grow:

name = "Kenji"
score = 87.5
print("Student: " + name + " | Score: " + str(score) + " / 100")

This works, but it is cluttered. Every number must be converted to a string manually. Every space must be placed carefully. A mistake anywhere breaks the output.

Introducing f-Strings

An f-string (formatted string literal) provides a cleaner way to embed variable values directly inside a string. An f-string starts with the letter f immediately before the opening quotation mark:

name = "Kenji"
score = 87.5
print(f"Student: {name} | Score: {score} / 100")
Student: Kenji | Score: 87.5 / 100

Inside an f-string, anything placed inside curly braces {} is treated as a Python expression. Python evaluates it and inserts the result into the string at that position. No manual str() conversion is needed.

Expressions Inside f-Strings

The {} can contain more than just variable names. Any Python expression works:

length = 8
width = 5
print(f"Area: {length * width} square units")

price = 12.99
quantity = 3
print(f"Total: {price * quantity}")
Area: 40 square units
Total: 38.97

Controlling Decimal Places

One of the most useful f-string features is the ability to control how many decimal places a float displays. You do this with a format specifier inside the braces:

temperature = 98.6123456
print(f"Temperature: {temperature:.2f}")
Temperature: 98.61
Reading the Format Specifier

The :.2f format specifier has three parts: a colon (:) that introduces the format; .2 specifying two decimal places; and f standing for "fixed-point notation." Together they mean: display this number as a fixed-point decimal with exactly 2 digits after the decimal point.

price = 4.5
print(f"Price: ${price:.2f}")
Price: $4.50

This is particularly useful for money calculations, where you almost always want exactly two decimal places.

More Format Specifiers

value = 3.14159
print(f"{value:.0f}")    # no decimal places
print(f"{value:.1f}")    # one decimal place
print(f"{value:.4f}")    # four decimal places (rounds)
3
3.1
3.1416

f-Strings in Practice

Here is a complete example that combines f-strings, type conversion, and multiple variables to produce clean, aligned output:

name = input("Enter student name: ")
score = float(input("Enter score (0-100): "))
passing = score >= 60

print(f"Student:  {name}")
print(f"Score:    {score:.1f} / 100")
print(f"Passing:  {passing}")

If the user enters Amara and 73.5:

Student:  Amara
Score:    73.5 / 100
Passing:  True
f-Strings Are the Preferred Style

Throughout this textbook, f-strings are the preferred method for producing formatted output that combines variables and text. They are readable, concise, and standard in professional Python code. When you are unsure whether to use concatenation, commas, or f-strings, choose f-strings.

Sections 4.9 – 4.10
Building and Testing Complete Programs
Input-Process-Output · Worked Examples · Test Cases · Debugging

Building Simple Interactive Programs

The Input-Process-Output Pattern

Almost every interactive program follows the same basic three-phase pattern:

Phase 1
Input
Receive data from the user using input(). Convert the data to the appropriate type. Store results in well-named variables.
Phase 2
Process
Do something with the data: calculate, compare, transform. Store intermediate results in variables. Keep calculations separate from display.
Phase 3
Output
Display the result clearly using print() and f-strings. Format numbers appropriately. Label every value so the output is self-explanatory.

This structure appears in tip calculators, unit converters, grade calculators, weather apps, quiz programs, and almost everything else. Learning to recognize and apply this pattern is one of the most important skills in this chapter.

Worked Example: Tip Calculator

Worked Example 4.9.1
Planning a tip calculator before writing code
  • GoalAsk for a restaurant bill total and a tip percentage. Calculate the tip amount and the total including tip.
  • InputBill total (float), tip percentage (float)
  • Processtip amount = bill × (tip percentage ÷ 100); total = bill + tip amount
  • OutputTip amount and total, formatted as currency with two decimal places
# Tip Calculator

# Input
bill = float(input("Enter the bill total ($): "))
tip_percent = float(input("Enter tip percentage (e.g. 18 for 18%): "))

# Process
tip_amount = bill * (tip_percent / 100)
total = bill + tip_amount

# Output
print()
print(f"Bill:      ${bill:.2f}")
print(f"Tip ({tip_percent:.0f}%): ${tip_amount:.2f}")
print(f"Total:     ${total:.2f}")

Sample run with inputs 45.00 and 20:

Bill:      $45.00
Tip (20%): $9.00
Total:     $54.00

Tracing the Tip Calculator

VariableValueHow it got there
bill45.0User typed 45.00; float() converted it
tip_percent20.0User typed 20; float() converted it
tip_amount9.045.0 * (20.0 / 100) = 45.0 * 0.2 = 9.0
total54.045.0 + 9.0 = 54.0

Worked Example: Temperature Converter

Goal: Ask for a Celsius temperature and convert it to Fahrenheit. Formula: Fahrenheit = Celsius × 9 / 5 + 32

# Temperature Converter: Celsius to Fahrenheit

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32

print(f"{celsius:.1f}°C is equal to {fahrenheit:.1f}°F")

Sample run with input 37:

37.0°C is equal to 98.6°F

Worked Example: Personalized Greeting

Goal: Ask for the user's name and birth year. Calculate their approximate age. Display a personalized greeting.

# Personalized Greeting

name = input("What is your name? ")
birth_year = int(input("What year were you born? "))

current_year = 2025
age = current_year - birth_year

print(f"Hello, {name}!")
print(f"You are approximately {age} years old.")

Sample run with inputs Leila and 2008:

Hello, Leila!
You are approximately 17 years old.
Skills Combine

Notice how these examples layer print(), comments, input(), prompts, type conversion, variables, arithmetic, and f-strings together. Programs do not use one skill at a time. They combine skills. The goal of this chapter is to make each individual skill automatic so that combining them feels natural.

Testing Simple Programs

Why Testing Matters

Writing a program is not the last step. After writing, you need to test it. Testing means running your program with specific inputs to check that it produces correct output. Even a small program like a tip calculator can produce wrong results if the formula contains a subtle error. Testing finds these problems before they matter.

What a Test Case Is

A test case is a specific input you run your program with, along with the output you expect. A good test case has:

  • A specific input value or set of values
  • The expected output for that input (calculated by hand or verified externally)
  • A check: does the actual output match the expected output?

Testing the Tip Calculator

BillTip %Expected TipExpected Total
50.0020$10.00$60.00
100.0015$15.00$115.00
0.0020$0.00$0.00
25.5010$2.55$28.05

Run your program with each of these inputs. If the actual output matches the expected output, the test passes. If not, something is wrong with the program.

Choosing Good Test Cases

Test Type
Typical Values
Normal inputs that represent the common case. These confirm the program works for its main purpose. Examples: 45.00 bill, 18% tip.
Test Type
Boundary Values
Values at the edges of what is expected: zero, very large numbers, minimum and maximum. These often reveal assumptions the programmer made without realizing it.
Test Type
Edge Cases
Unusual or extreme inputs: negative numbers, decimals where integers are expected, empty input, very long strings. These test the limits of your program's assumptions.

Testing the Temperature Converter

Celsius InputExpected FahrenheitWhy This Case Matters
032.0Freezing point — well-known value to verify
100212.0Boiling point — another well-known check
-40-40.0The only temperature equal in both scales; tests negatives
3798.6Normal body temperature — practical check

The -40 case is interesting: −40°C equals −40°F. It is a natural boundary case that tests whether the formula works for negative numbers. A formula error would produce a different result for negatives even if all positive tests passed.

Print-Style Debugging

When a program produces wrong output, the first step is to trace what is actually happening. One technique is to add temporary print() calls to inspect intermediate values:

bill = float(input("Enter the bill total ($): "))
tip_percent = float(input("Enter tip percentage: "))

print(f"DEBUG: bill = {bill}, tip_percent = {tip_percent}")   # temporary

tip_amount = bill * (tip_percent / 100)

print(f"DEBUG: tip_amount = {tip_amount}")    # temporary

total = bill + tip_amount
print(f"Total: ${total:.2f}")

These DEBUG lines let you see whether the variables hold the values you expect. Once the program works correctly, remove the debug lines. This technique — inserting print() calls to trace program behavior — is one of the most practical debugging methods you will use throughout your programming career.

Reading Error Messages

When Python encounters a problem it cannot handle, it stops and prints an error message. Learning to read error messages is an essential skill. Consider what happens if someone types a word instead of a number:

ValueError: could not convert string to float: 'fifty'

The error message tells you the error type (ValueError), what went wrong (it could not convert the string 'fifty' to a float), and a line number pointing to exactly where in your program the problem occurred. Read error messages from top to bottom. The last line usually describes the problem most directly.

Common Error Types in This Chapter

Error TypeTypical CauseExample
TypeErrorTrying to concatenate a string and a number without conversion"Score: " + 95
ValueErrorPassing a non-numeric string to int() or float()int("hello")
NameErrorUsing a variable name before assigning it a valueprint(score) before score =
SyntaxErrorA typo, missing parenthesis, or unclosed quotation markprint("hello'

Chapter Summary

Key Terms

argument
A value passed to a function inside the parentheses of a function call. In print("Hello"), "Hello" is the argument.
boundary value
A test input at the edge of what a program expects, such as zero, a negative number, or a very large number. Boundary values often reveal hidden assumptions in a program.
comment
Text in source code that Python ignores during execution, marked with #. Comments are written for human readers to explain purpose, reasoning, or structure.
concatenation
Joining two strings together with the + operator. "Hello" + " world" produces "Hello world". No automatic spacing is added.
conversion
Changing a value from one data type to another using functions like int(), float(), or str().
edge case
An input that is unusual, extreme, or at the outer boundary of what a program might receive, such as an empty string or a zero value.
f-string
A formatted string literal written with an f prefix before the quotation mark. Variables and expressions inside {} braces are embedded directly in the string.
floor division
Division using the // operator that produces an integer result by discarding any remainder. 7 // 2 produces 3, not 3.5.
format specifier
A code inside {} braces in an f-string that controls how a value is displayed. :.2f formats a float to exactly two decimal places.
float()
A built-in function that converts a value to a floating-point number. Handles both integer strings ("7") and decimal strings ("3.14").
input()
A built-in Python function that displays a prompt, pauses execution, waits for the user to type something and press Enter, and returns the typed text as a string.
input-process-output
A fundamental program structure: gather data from the user (input), perform computation or transformation (process), and display the result (output).
int()
A built-in function that converts a value to an integer. Truncates floats (does not round). Raises a ValueError if given a non-numeric string.
print-style debugging
A debugging technique that inserts temporary print() calls into a program to inspect variable values during execution. Debug lines are removed once the program works correctly.
print()
A built-in Python function that displays values to the screen. Accepts multiple values separated by commas and automatically adds spaces between them and a newline at the end.
prompt
The string argument passed to input() that tells the user what to type. A good prompt is specific and ends with a space or colon-space.
str()
A built-in function that converts a value to a string. Essential when using string concatenation with numeric values.
test case
A specific input value (or set of values) paired with the expected output, used to verify that a program behaves correctly.
truncation
Dropping the fractional part of a number without rounding. int(3.9) produces 3, not 4. Truncation always moves toward zero.
TypeError
A runtime error that occurs when an operation is applied to a value of the wrong type, such as adding a string and an integer without conversion.
ValueError
A runtime error that occurs when a function receives a value of the right type but inappropriate content — for example, calling int("hello").

Concept Check

Answer these questions before beginning the full review questions. They check basic understanding, not deep analysis.

  1. What does print() do when called with no arguments?
  2. What is the difference between print(x, y) and print(x + y) when x = 3 and y = 4?
  3. What does input() always return, regardless of what the user types?
  4. Why does the statement age = input("Age: ") followed by print(age + 1) cause an error?
  5. What is the difference between int(3.9) and round(3.9)?
  6. Write a single line that asks the user for a number and stores it as a float in a variable called amount.
  7. What does the f in f"..." signal to Python?
  8. What does the format specifier :.2f do?
  9. Name the three phases of the input-process-output pattern.
  10. What kind of error is it when a program runs without crashing but produces wrong output?

Common Misconceptions

Misconception 1
"If the user types a number, input() gives me a number."
input() always returns a string. Always. If the user types 42, your program receives the string "42", not the integer 42. You must call int() or float() to convert it before doing arithmetic. This is one of the most common sources of TypeError bugs in early Python programs.
Misconception 2
"int(3.9) gives me 4 because 3.9 rounds up."
int() truncates — it drops the decimal part entirely, moving toward zero. int(3.9) gives 3, not 4. int(-2.7) gives -2, not -3. If you need rounding, use round(). The distinction matters whenever you are converting measurements, scores, or any value where the fractional part carries meaning.
Misconception 3
"Commenting every line makes my code better."
Over-commenting clutters code and can actually make it harder to read. A comment that says # add 1 to x next to x = x + 1 adds no value. Good comments explain purpose and reasoning, not what the code already says plainly. Clear variable names often do more for readability than comments do.
Misconception 4
"My program is finished once it runs without crashing."
A program that runs without errors can still produce wrong output. Logic errors — mistakes in the computation or program design — do not cause crashes. They just produce incorrect results silently. Testing with known inputs and checking expected outputs is the only way to confirm a program is actually correct.
Misconception 5
"I can use + to combine a string and a number in print()."
The + operator between a string and a number raises a TypeError. You must either convert the number to a string with str(), or use an f-string instead. F-strings handle this automatically and are the preferred approach.
PracticeInput and Output Practice
  1. Write a print() statement that displays the following on a single line: Name: Taylor Age: 22 City: Denver
  2. What does this code display?
    x = 10
    y = 3
    print(x, "+", y, "=", x + y)
  3. Write three separate print() statements that produce this output (including the blank lines):
    Section 1: Introduction
    
    Section 2: Main Content
    
    Section 3: Conclusion
  4. What is the difference between these two print statements? Do they produce the same output?
    print("Score:", 95)
    print("Score: " + str(95))
  5. Write a print() statement using sep so that the values "2025", "11", and "04" are displayed separated by forward slashes: 2025/11/04
  6. Write an input() statement that asks the user for their favorite color and stores the response in a variable called color. Then write a print() statement that displays the response.
  7. What does input() always return, regardless of what the user types?
  8. A student writes the following program:
    age = input("Enter your age: ")
    print("In ten years you will be", age + 10)
    What error will occur? What should be changed to fix it?
PracticeType Conversion Practice
  1. What does each of the following expressions evaluate to?
    int("50")
    float("3.14")
    str(7)
    int(9.99)
    float(4)
    str(True)
  2. A program receives a value from input() and needs to compute value * 2. Write the correct code to receive the input and perform the multiplication, assuming the input will be a whole number.
  3. What is the result of int(7.9)? What is the result of int(-2.3)? Does int() round or truncate?
  4. Which conversion function should you use when the user might enter a value like "12.5"? Why would int() not work?
  5. A program stores the result of a calculation in a variable called result. Write a print() statement using string concatenation that displays "The result is: " followed by the value of result. (Assume result is a float.)
  6. Write a short program that asks for the user's birth year as input, converts it to an integer, subtracts it from 2025 to calculate an approximate age, and prints the result.
PracticePredict the Output

For each code block, predict exactly what will be displayed before running it. Then run it to check.

  1. x = 5
    y = 2
    print(f"{x} times {y} equals {x * y}")
  2. name = "Jordan"
    score = 91.4
    print(f"Student: {name}")
    print(f"Score: {score:.0f}%")
  3. a = 7
    b = 3
    print(f"{a} divided by {b} is approximately {a / b:.2f}")
  4. total = 150
    discount = 0.20
    final = total * (1 - discount)
    print(f"Original: ${total:.2f}")
    print(f"Discount: {discount * 100:.0f}%")
    print(f"Final price: ${final:.2f}")
  5. print("Hello", end=" ")
    print("from", end=" ")
    print("Python!")
  6. width = 8
    height = 5
    area = width * height
    perimeter = 2 * (width + height)
    print(f"Rectangle: {width} x {height}")
    print(f"Area:      {area}")
    print(f"Perimeter: {perimeter}")
PracticeDebugging Practice

Each program below contains at least one error. Identify the error, explain what is wrong, and write a corrected version.

  1. name = input("What is your name? ")
    age = input("What is your age? ")
    print("Hello " + name + ". Next year you will be " + age + 1 + ".")
  2. price = float(input("Enter price: ")
    tax = price * 0.08
    print(f"Tax: ${tax:.2f}")
  3. miles = input("Enter distance in miles: ")
    kilometers = miles * 1.60934
    print(f"{miles} miles = {kilometers:.2f} km")
  4. radius = float(input("Enter radius: "))
    area = 3.14159 * radius ^ 2
    print(f"Area: {area:.2f}")
    (Hint: Python does not use ^ for exponentiation.)
  5. first = input("First number: ")
    second = input("Second number: ")
    total = first + second
    print("Sum:", total)
    This program runs without crashing, but produces wrong output when the user enters numbers. What is happening, and how do you fix it?
  6. name = input("Name: ")
    score = float(input("Score: "))
    print(f"Student (name) earned a (score:.1f)%.")
    What is wrong with the f-string? Write the correct version.
TasksShort Programming Tasks
  1. Write a program that asks for a rectangle's length and width (as floats), then displays the area and perimeter using an f-string.
  2. Write a program that asks for a person's name, their hourly wage (as a float), and the number of hours worked (as a float). Display the total earnings rounded to two decimal places.
  3. Write a program that asks for the price of an item and displays the price with 8% tax added, formatted to two decimal places.
  4. Write a program that asks the user to enter their first name and last name separately, then displays their full name and the number of characters in their full name combined (not counting the space). Hint: len("hello") returns 5.
  5. Write a program that converts miles per hour to kilometers per hour. (1 mile = 1.60934 km.) Ask for the speed in mph and display the result in km/h, formatted to one decimal place.
  6. Write a program that asks for a student's score on each of three tests (as integers) and displays the average score formatted to one decimal place.
  7. Write a program that displays a simple receipt for a purchase. Ask for the item name, the unit price (float), and the quantity (integer). Display a formatted receipt:
    Item:     Widget
    Qty:      3
    Price:    $4.99 each
    Subtotal: $14.97
  8. Write a program that asks for a temperature in Fahrenheit and converts it to Celsius. Formula: Celsius = (Fahrenheit − 32) × 5 / 9. Display the result to one decimal place.
Mini-Project — Chapter 4
Unit Converter

Overview

Build a small interactive unit converter in Python. Your program should convert between at least three pairs of units. Use good prompts, type conversion, f-strings for formatted output, and comments to organize your code.

Requirements

  1. Display a brief welcome message explaining what the program does.
  2. Ask the user to enter a value to convert.
  3. Perform at least three conversions on that value (displayed simultaneously), or ask the user which conversion to perform.
  4. Display each result formatted to two decimal places.
  5. Include comments explaining each section of the program.

Suggested Unit Pairs

Choose at least three pairs, or design your own:

FromToFormula
KilometersMilesmiles = km × 0.621371
MilesKilometerskm = miles × 1.60934
KilogramsPoundslbs = kg × 2.20462
CelsiusFahrenheitF = C × 9/5 + 32
MetersFeetfeet = meters × 3.28084
LitersGallonsgallons = liters × 0.264172
InchesCentimeterscm = inches × 2.54

Example Output

=== Unit Converter ===

Enter a distance in kilometers: 10

10.00 km = 6.21 miles
10.00 km = 10000.00 meters
10.00 km = 32808.40 feet

Testing Your Converter

Before finishing, test your program with these cases: a typical value (e.g., 10), zero (0), a decimal value (e.g., 3.5), and a large value (e.g., 1000). Check your results against an online converter or manual calculation. If any output is wrong, trace through the formula to find the mistake.

Extension (Optional)

After displaying results, ask the user if they want to convert another value. Use a simple yes_or_no = input("Convert another value? (yes/no): ") and handle the response with an if statement — but only if you feel ready. You will study conditionals in depth in Chapters 5 and 6.

ReviewReview Questions

Recall and Vocabulary

  1. What does print() do when called with no arguments?
  2. What is the difference between print(x, y) and print(x + y) when x = 3 and y = 4?
  3. What are two reasons to write comments in your code?
  4. True or false: input() can return an integer if the user types a number. Explain your answer.
  5. Why is the combined form age = int(input("Enter age: ")) useful? What does it accomplish in one line?
  6. What will happen if a user types "twenty" when a program calls int(input("Enter a number: "))? What kind of error occurs?
  7. What is an f-string? Write a short example using a variable called city and a variable called population.
  8. What does the format specifier :.2f do in an f-string?

Understanding and Explanation

  1. Describe the input-process-output pattern. Give an example of a program that follows this pattern.
  2. What is a test case? Give an example of a good test case for a program that calculates the area of a circle.
  3. What is print-style debugging? When would you use it?
  4. A program produces the wrong numerical result but does not raise any error. What kind of error is this: syntax error, runtime error, or logic error? What is the best strategy for finding it?
  5. Explain the difference between print("Score:", score) and print(f"Score: {score}"). When might you prefer one over the other?
  6. Why does int(3.9) return 3 rather than 4? When is this behavior important to understand?

Application and Analysis

  1. A student writes the following program to calculate the area of a triangle:
    base = input("Enter the base: ")
    height = input("Enter the height: ")
    area = base * height / 2
    print(f"Area: {area:.2f}")
    The program crashes with a TypeError. Explain why, identify exactly what needs to change, and write the corrected version.
  2. A program asks the user for a price and a discount percentage and calculates the final price. Write the program using the input-process-output structure with clear comments separating each phase. Test it with at least three cases.
  3. Explain what happens step by step when Python executes this line: weight = float(input("Enter your weight in kg: "))
  4. Compare these two approaches for displaying a greeting. What are the advantages of each? Which would you prefer and why?
    print("Hello, " + name + "! You are " + str(age) + " years old.")
    print(f"Hello, {name}! You are {age} years old.")

Design and Synthesis

  1. Plan a program that asks a student for their name and scores on four assignments, then displays a summary showing their name, each score, and the average. Write the plan in input-process-output form before writing any code. Then write the complete program.
  2. Write a program that works as a simple personal information card. Ask the user for their name, city, and birth year. Display a formatted card like this, adjusting the values based on input:
    ╔═════════════════════════╗
      Name:    Jordan Lee
      City:    Portland
      Born:    2001
      Age:     24
    ╚═════════════════════════╝
    (You can approximate the border with dashes if special characters are unavailable.)
Chapter 4 Checklist
Use this to confirm your understanding before moving to Chapter 5
Output
  • I can use print() to display strings, numbers, variables, and expressions.
  • I understand the difference between comma-separated values and string concatenation in print().
  • I can produce a blank line with print().
  • I know what end and sep do and can use them when needed.
Comments and Style
  • I can write comments using # that explain purpose, not just syntax.
  • I use blank lines to separate logical sections of code.
  • I understand what makes a comment useful versus redundant.
Input
  • I can use input() with a clear, specific prompt to receive user input.
  • I understand that input() always returns a string, regardless of what the user types.
  • I can ask for multiple inputs using multiple input() calls.
Type Conversion
  • I can use int(), float(), and str() to convert between types.
  • I know the standard idiom: x = int(input("...")).
  • I understand that int() truncates floats rather than rounding them.
  • I know which conversion function to choose when user input may contain decimals.
f-Strings
  • I can write an f-string that embeds a variable using {}.
  • I can embed a Python expression inside {} in an f-string.
  • I can use :.2f to format a float to two decimal places.
  • I understand why f-strings are generally preferred over concatenation.
Programs and Testing
  • I can structure a simple program around the input-process-output pattern.
  • I can design test cases with typical values, boundary values, and edge cases.
  • I can use print-style debugging to trace variable values.
  • I can read a Python error message and identify the error type and location.
Preview — Chapter 5
Booleans, Comparisons, and Decisions

Chapter 4 has given your programs a voice — they can ask questions and display results. But your programs still cannot decide. Every program you have written so far runs the same instructions in the same order every time, regardless of what the user types.

Chapter 5 introduces Boolean values and comparison operators — the tools that let programs evaluate conditions and prepare for branching. You will learn how Python represents True and False, how to compare values using operators like <, ==, and >=, how to combine conditions with and, or, and not, and how to design decision rules clearly before translating them into code. Chapter 6 will then teach the if, elif, and else statements that execute different instructions depending on which conditions are true. Together, Chapters 5 and 6 mark the transition from programs that simply calculate to programs that genuinely reason.

MGU Library Connection
  • Programming with Python — Appendix C: Python Syntax Quick Reference
  • Programming with Python — Appendix D: Common Python Error Messages
  • Companion resource: Variable Tracing Worksheet
  • Companion resource: Debugging Checklist
  • Companion resource: Python Syntax Quick Reference Card
  • Companion resource: Common Python Errors Guide
  • Prerequisite chapter: Chapter 3 — Values, Variables, and Expressions
  • Next chapter: Chapter 5 — Booleans, Comparisons, and Decisions