How programs speak and listen — displaying results, receiving user input, converting types, formatting output with f-strings, and building your first complete interactive programs
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.
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.
By the end of this chapter, you should be able to:
print() to display strings, numbers, variables, and computed expressions.input() with a clear prompt to receive text from a user and store it in a variable.input() always returns a string, even when the user types a number.int(), float(), and str() to convert values between types.input() and a conversion function in a single statement using the standard Python idiom.:.2f format specifier to display floats with a controlled number of decimal places.print()Displaying values, strings, numbers, expressions; printing multiple values with commas; blank output; the end and sep parametersprint() can display; printing computed results; displaying variables; division and floats; floor division# symbol; why comments matter; what to comment and what not to comment; blank lines for visual organizationinput()How input() works; the execution flow when a program pauses; why input() always returns a string; the prompt argumentinput(); why arithmetic on string input fails; string concatenation; concatenation versus comma-separated printingint(), float(), and str(); converting strings to numbers; the combined input+conversion idiom; truncation versus rounding; what happens when conversion fails; conversion reference tablef"..." syntax; embedding variables and expressions with {}; the :.2f format specifier; controlling decimal places; why f-strings are preferredprint()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.
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.
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
end ParameterBy 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.
sep ParameterYou can also control what goes between values using the sep parameter:
print("2025", "06", "15", sep="-")
2025-06-15
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.
print() Can Displayprint() 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
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
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 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
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.
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
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
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.
input()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
input() Works — Step by Stepinput() callinput() with the prompt string "What is your name? ".input() returns everything the user typed, as a string.name.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 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: ")
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.
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 Prompt | Clear Prompt | What 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 |
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.
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")
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.
input() Is a StringWhen 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.
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.
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.
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.
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.
Python provides built-in functions for converting values from one type to another. The three most important for this chapter are:
int()"42" and on floats (truncates — does not round). Fails on non-numeric strings.float()"100" and on decimal strings like "3.14". More flexible than int() for user input.str()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: "))
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.
float() for Decimal InputWhen 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
float() When Input May Contain Decimalsfloat() 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().
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.
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.
| Expression | Result | Notes |
|---|---|---|
int("42") | 42 | String to integer |
int(3.9) | 3 | Float to integer — truncates, does not round |
int(-2.7) | -2 | Truncation moves toward zero |
float("3.14") | 3.14 | String to float |
float(7) | 7.0 | Integer to float |
str(100) | "100" | Integer to string |
str(3.14) | "3.14" | Float to string |
str(True) | "True" | Boolean to string |
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.
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.
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.
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
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
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.
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
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
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.
Almost every interactive program follows the same basic three-phase pattern:
input(). Convert the data to the appropriate type. Store results in well-named variables.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.
# 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
| Variable | Value | How it got there |
|---|---|---|
bill | 45.0 | User typed 45.00; float() converted it |
tip_percent | 20.0 | User typed 20; float() converted it |
tip_amount | 9.0 | 45.0 * (20.0 / 100) = 45.0 * 0.2 = 9.0 |
total | 54.0 | 45.0 + 9.0 = 54.0 |
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
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.
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.
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.
A test case is a specific input you run your program with, along with the output you expect. A good test case has:
| Bill | Tip % | Expected Tip | Expected Total |
|---|---|---|---|
| 50.00 | 20 | $10.00 | $60.00 |
| 100.00 | 15 | $15.00 | $115.00 |
| 0.00 | 20 | $0.00 | $0.00 |
| 25.50 | 10 | $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.
45.00 bill, 18% tip.| Celsius Input | Expected Fahrenheit | Why This Case Matters |
|---|---|---|
| 0 | 32.0 | Freezing point — well-known value to verify |
| 100 | 212.0 | Boiling point — another well-known check |
| -40 | -40.0 | The only temperature equal in both scales; tests negatives |
| 37 | 98.6 | Normal 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.
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.
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.
| Error Type | Typical Cause | Example |
|---|---|---|
TypeError | Trying to concatenate a string and a number without conversion | "Score: " + 95 |
ValueError | Passing a non-numeric string to int() or float() | int("hello") |
NameError | Using a variable name before assigning it a value | print(score) before score = |
SyntaxError | A typo, missing parenthesis, or unclosed quotation mark | print("hello' |
print() displays values, expressions, and combinations of text and data. It accepts multiple values separated by commas, automatically placing spaces between them. The end and sep parameters give additional control over output formatting.print() can display strings, integers, floats, Booleans, and expressions. Division with / always returns a float; use // for integer results. Displaying a variable shows its current value, not its name.#, let programmers explain their code for human readers without affecting execution. Good comments explain why, not just what. Blank lines provide visual organization. Both make programs easier to understand and maintain.input() pauses a program, shows a prompt, waits for a response, and returns whatever the user typed as a string. The result is always a string, regardless of what the user typed. Always provide a clear, informative prompt.input() calls gather several values in sequence. Organizing code into input, process, and output phases makes programs easier to read and debug.input() always returns a string. Arithmetic on string input fails with a TypeError. String concatenation with + joins strings without automatic spacing; this is different from comma-separated printing.int(), float(), and str() — convert values between types. Because input() always returns a string, converting to a number before arithmetic is essential. The combined form age = int(input("...")) is the standard Python idiom. Converting a float to int truncates, not rounds.f"..." syntax and {} braces. The :.2f format specifier controls the number of decimal places in float output. F-strings are the preferred method for formatted output in Python.print() calls to trace variable values. Reading error messages carefully identifies the cause and location of problems.print("Hello"), "Hello" is the argument.#. Comments are written for human readers to explain purpose, reasoning, or structure.+ operator. "Hello" + " world" produces "Hello world". No automatic spacing is added.int(), float(), or str().f prefix before the quotation mark. Variables and expressions inside {} braces are embedded directly in the string.// operator that produces an integer result by discarding any remainder. 7 // 2 produces 3, not 3.5.{} braces in an f-string that controls how a value is displayed. :.2f formats a float to exactly two decimal places.float()"7") and decimal strings ("3.14").input()int()ValueError if given a non-numeric string.print() calls into a program to inspect variable values during execution. Debug lines are removed once the program works correctly.print()input() that tells the user what to type. A good prompt is specific and ends with a space or colon-space.str()int(3.9) produces 3, not 4. Truncation always moves toward zero.TypeErrorValueErrorint("hello").Answer these questions before beginning the full review questions. They check basic understanding, not deep analysis.
print() do when called with no arguments?print(x, y) and print(x + y) when x = 3 and y = 4?input() always return, regardless of what the user types?age = input("Age: ") followed by print(age + 1) cause an error?int(3.9) and round(3.9)?amount.f in f"..." signal to Python?:.2f do?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.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.# 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.+ to combine a string and a number in print()."+ 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.print() statement that displays the following on a single line: Name: Taylor Age: 22 City: Denverx = 10
y = 3
print(x, "+", y, "=", x + y)print() statements that produce this output (including the blank lines):
Section 1: Introduction Section 2: Main Content Section 3: Conclusion
print("Score:", 95)
print("Score: " + str(95))print() statement using sep so that the values "2025", "11", and "04" are displayed separated by forward slashes: 2025/11/04input() 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.input() always return, regardless of what the user types?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?int("50")
float("3.14")
str(7)
int(9.99)
float(4)
str(True)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.int(7.9)? What is the result of int(-2.3)? Does int() round or truncate?"12.5"? Why would int() not work?result. Write a print() statement using string concatenation that displays "The result is: " followed by the value of result. (Assume result is a float.)For each code block, predict exactly what will be displayed before running it. Then run it to check.
x = 5
y = 2
print(f"{x} times {y} equals {x * y}")
name = "Jordan"
score = 91.4
print(f"Student: {name}")
print(f"Score: {score:.0f}%")
a = 7
b = 3
print(f"{a} divided by {b} is approximately {a / b:.2f}")
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}")
print("Hello", end=" ")
print("from", end=" ")
print("Python!")
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}")
Each program below contains at least one error. Identify the error, explain what is wrong, and write a corrected version.
name = input("What is your name? ")
age = input("What is your age? ")
print("Hello " + name + ". Next year you will be " + age + 1 + ".")
price = float(input("Enter price: ")
tax = price * 0.08
print(f"Tax: ${tax:.2f}")
miles = input("Enter distance in miles: ")
kilometers = miles * 1.60934
print(f"{miles} miles = {kilometers:.2f} km")
radius = float(input("Enter radius: "))
area = 3.14159 * radius ^ 2
print(f"Area: {area:.2f}")
(Hint: Python does not use ^ for exponentiation.)
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?
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.
len("hello") returns 5.Item: Widget Qty: 3 Price: $4.99 each Subtotal: $14.97
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.
Choose at least three pairs, or design your own:
| From | To | Formula |
|---|---|---|
| Kilometers | Miles | miles = km × 0.621371 |
| Miles | Kilometers | km = miles × 1.60934 |
| Kilograms | Pounds | lbs = kg × 2.20462 |
| Celsius | Fahrenheit | F = C × 9/5 + 32 |
| Meters | Feet | feet = meters × 3.28084 |
| Liters | Gallons | gallons = liters × 0.264172 |
| Inches | Centimeters | cm = inches × 2.54 |
=== 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
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.
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.
print() do when called with no arguments?print(x, y) and print(x + y) when x = 3 and y = 4?input() can return an integer if the user types a number. Explain your answer.age = int(input("Enter age: ")) useful? What does it accomplish in one line?"twenty" when a program calls int(input("Enter a number: "))? What kind of error occurs?city and a variable called population.:.2f do in an f-string?print("Score:", score) and print(f"Score: {score}"). When might you prefer one over the other?int(3.9) return 3 rather than 4? When is this behavior important to understand?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.weight = float(input("Enter your weight in kg: "))print("Hello, " + name + "! You are " + str(age) + " years old.")
print(f"Hello, {name}! You are {age} years old.")╔═════════════════════════╗ Name: Jordan Lee City: Portland Born: 2001 Age: 24 ╚═════════════════════════╝(You can approximate the border with dashes if special characters are unavailable.)
print() to display strings, numbers, variables, and expressions.print().print().end and sep do and can use them when needed.# that explain purpose, not just syntax.input() with a clear, specific prompt to receive user input.input() always returns a string, regardless of what the user types.input() calls.int(), float(), and str() to convert between types.x = int(input("...")).int() truncates floats rather than rounding them.{}.{} in an f-string.:.2f to format a float to two decimal places.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.