MGU Computer Science Series — Computer Science Foundations
Part II: Programming Foundations
Variables · Types · Expressions · State · Input and Output
Chapter 7 of 28
MGU Computer Science Series  ·  Computer Science Foundations  ·  Library Textbook Edition

Chapter 7:
Variables, Types,
and Expressions

How programs store information, represent different kinds of data, build expressions from values and operators, and track changing state over time

■ Part II: Programming Foundations ■

■ 10 Sections  •  Chapter 7 of 28 ■

Follows Chapter 6: Programming Languages and Code  ·  Prepares students for Chapter 8: Conditionals, Loops, and Control Flow

Purpose and Overview

Every program that does anything useful has to remember information. It stores a name, a score, a temperature, a password, a running total. It works with that information — comparing values, adding numbers, joining words together, checking whether something is true or false. This chapter is about how programs do that: through variables, types, expressions, and the idea of state.

These ideas are not unique to Python or to any one language. Variables, values, types, expressions, and assignment appear in Python, JavaScript, Java, C, Rust, and nearly every other language you will encounter. The syntax changes from language to language, but the underlying logic stays the same. This chapter uses Python-style examples because Python's syntax is clear and readable for learning. The goal, however, is not to memorize Python. The goal is to build the mental model that will carry you through Chapter 8 and every programming course beyond this one.

Opening Question

A program needs to track a player's score in a game. The score starts at zero, increases when the player earns points, and decreases when the player loses a life. How should the program remember this value? How does it update it? How does it display it on screen? By the end of this chapter, you will know exactly how — and why the same pattern applies to prices, temperatures, names, usernames, and every other piece of information a program manages.

10Sections
11Objectives
20Key Terms
12+Worked Examples

Learning Objectives

  1. 1Explain what a value and a variable are, and describe the role of variables in programs.
  2. 2Trace assignment statements step by step, including reassignment and accumulator patterns.
  3. 3Identify the type of any basic value: integer, float, string, or Boolean.
  4. 4Perform and interpret integer arithmetic, including integer division and the remainder operator.
  5. 5Describe what strings are and apply string operations including concatenation, repetition, and indexing.
  6. 6Construct and evaluate Boolean expressions using comparison and Boolean operators.
  7. 7Apply operator precedence rules and use parentheses to control evaluation order.
  8. 8Use input() and print() correctly, including type conversion from input strings.
  9. 9Perform explicit type conversions and explain the difference between int, float, str, and bool conversions.
  10. 10Describe a program's state and trace it through a sequence of assignments using a trace table.
  11. 11Read simple programs and predict their output correctly.

Sections at a Glance

Sections 7.1 – 7.2
Values, Variables, and Assignment
What Values Are · Variables as Named Storage · The Assignment Statement · Trace Tables

Values and Variables

What a Value Is

A value is a piece of information a program can use. Values come in many forms: the number 42, the word "hello", the measurement 3.14, or the truth-or-false choice True. Every piece of data in a program is a value. Values by themselves are temporary — if a program computes a result and nothing stores it, that result disappears as soon as the line finishes executing.

What a Variable Is

A variable is a named storage location that holds a value. When a program creates a variable, it gives a name to a piece of memory so that value can be referred to later. Think of a variable as a labeled box: the label is the variable's name, and the contents of the box are the variable's value. The box can hold different contents at different times.

The Variable Mental Model

variable name: score

variable value: 95

A program can read from the box (look at the score), write to the box (change the score), or pass the box's contents somewhere else (display the score, or add it to another number).

Variable Naming Rules

In Python, variable names can contain letters, digits, and underscores. Names must start with a letter or underscore — not a digit. Names are case-sensitive: score, Score, and SCORE are three different variables. Names should be descriptive: total_score is clearer than ts.

Good Variable NamesPoor Variable NamesWhy Poor?
agexUnclear meaning
first_nametemp2Ambiguous — temperature? temporary?
temperature_celsiusa1b2c3Unreadable
number_of_students1scoreStarts with a digit — invalid
is_logged_inIsLoggedInInconsistent style; not conventional Python
Habit of Mind

The habit of writing clear variable names is one of the most valuable habits in programming. It makes programs readable — for other programmers, and for your future self who may return to the code months later with no memory of what x was supposed to mean.

Practice 7.1Variables Concept Check
  1. In your own words, explain the difference between a value and a variable. Give one example of each.
  2. Why is it useful to give a variable a descriptive name rather than a single letter?
  3. Which of the following are valid Python variable names? For those that are invalid, explain why.

    first_name  ·  2ndScore  ·  total_cost  ·  my variable  ·  _count  ·  MAX

Assignment

The Assignment Statement

An assignment statement stores a value into a variable. In Python, the assignment operator is a single equals sign (=). The left side is always a variable name; the right side is always a value or expression that produces a value. The = sign does not mean "equals" in the mathematical sense — it means "store this value into this variable."

age = 17
score = 100
name = "Jordan"
temperature = 98.6
is_active = True

After these five lines execute, five variables exist, each holding a value of a different type.

Reassignment

A variable can be reassigned as many times as needed. Each assignment replaces the previous value entirely — the earlier value is gone.

score = 100
score = 95
score = 87
print(score)   # Output: 87

The Right Side Evaluates First

An important rule: the right side of an assignment is fully evaluated before anything is stored. This makes the pattern x = x + 1 valid — and very common in programming.

x = 5
x = x + 1    # look up x (5), add 1, get 6, store 6 in x
print(x)      # Output: 6
Mathematical vs. Programming Meaning

In mathematics, x = x + 1 is impossible — no number equals itself plus one. In programming, = is not equality; it is an instruction. It means: "evaluate the right side, then store the result in the variable on the left." The earlier value of x is used in computing the new value, then replaced.

Trace Tables

A trace table records the values of variables through each step of a program's execution. Tracing is the most reliable way to understand what a program does and to find errors.

Example 7.2.1
Tracing assignment statements
  • Program a = 10 b = 3 a = a + b b = a - b print(a) print(b)
  • Trace
    StepStatementab
    1a = 1010—
    2b = 3103
    3a = a + b133
    4b = a - b1310
Output: 13  then  10
Practice 7.2Assignment Tracing

Build a trace table for each program and write the output.

  1. x = 8  /  y = 3  /  x = x * y  /  print(x)
  2. a = 20  /  b = a // 3  /  c = a % 3  /  print(b)  /  print(c)
  3. name = "Alex"  /  greeting = "Hello, " + name  /  print(greeting)
Sections 7.3 – 7.5
Data Types: Numbers, Strings, and Booleans
Integers · Floats · Arithmetic Operators · Strings · Indexing · Booleans · Truth Tables

Numbers

Integers

An integer (type int) is a whole number with no decimal point. Integers can be positive, negative, or zero. They are used for counting, indexing, and any situation where fractional values do not make sense — you cannot have 2.7 students.

students = 30
temperature = -5
items = 0
year = 2025

Floats

A float (type float) is a number with a decimal point, representing real-world measurements that are not always whole numbers.

price = 4.99
height = 1.75
pi = 3.14159

Arithmetic Operators

OperatorMeaningExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
**Exponentiation2 ** 416
//Integer division7 // 32
%Remainder (modulo)7 % 31
/Division (float result)7 / 32.333...

Integer division (//) divides and keeps only the whole number portion, discarding the remainder. 7 // 3 gives 2 because 3 goes into 7 twice with something left over. The remainder operator (%) gives what is left after integer division. 7 % 3 gives 1 because 7 = (3 × 2) + 1.

Example 7.3.1
Converting minutes into hours and minutes
  • ProblemA program receives a total of 137 minutes. Break it into full hours and remaining minutes.
  • Solve minutes = 137 hours = minutes // 60 # 137 // 60 = 2 remaining = minutes % 60 # 137 % 60 = 17
  • Check2 × 60 = 120; 120 + 17 = 137. ✓
Output: 2 full hours, 17 minutes remaining.
Two Division Traps

Dividing by zero causes a ZeroDivisionError and stops the program. Always ensure the divisor cannot be zero before dividing.

Mixing division types: 7 / 2 produces 3.5 in Python — not 3. If you want integer division, use 7 // 2.

Practice 7.3Number Operations
  1. 15 + 4 * 3
  2. 20 // 6
  3. 20 % 6
  4. 3 ** 3
  5. 100 / 8
  6. 100 // 8
  7. 17 % 5
  8. 2 ** 10

Also: A program receives 245 seconds. Using // and %, compute the full minutes and remaining seconds. Show your work.

Strings

A string is a sequence of characters — letters, digits, punctuation, spaces, or any other symbol — treated as text. Strings are enclosed in quotation marks. Both single quotes and double quotes work in Python; the convention is to be consistent. The value "42" and the value 42 are completely different: one is a string, one is an integer.

String Operations

OperationOperatorExampleResult
Concatenation (join)+"Hello" + " World""Hello World"
Repetition*"-" * 10"----------"
Lengthlen()len("hello")5
Indexing[]"hello"[1]"e"

Zero-Based Indexing

A string is a sequence of individual characters, each at a numbered position called an index. In Python — and most languages — indexes start at zero, not one.

Index Positions in a String

String: a l g o r i t h m

Index: 0 1 2 3 4 5 6 7 8

The string "algorithm" has 9 characters. The first is at index 0; the last is at index 8. This off-by-one pattern appears throughout programming — lists, arrays, and all sequences behave the same way.

word = "algorithm"
print(word[0])    # a
print(word[4])    # r
print(word[8])    # m
print(len(word)) # 9

f-Strings

An f-string (formatted string literal) lets you embed variable values directly inside a string. Place an f before the opening quote and put variable names or expressions inside {}.

name = "Jordan"
score = 94
print(f"Student: {name}, Score: {score}")
# Output: Student: Jordan, Score: 94
Strings Are Not Numbers

"42" is a string. 42 is an integer. You cannot mix them with + directly. Writing "Score: " + 94 will cause a TypeError. Use an f-string or str(94) to convert first.

Practice 7.4String Operations
  1. len("computer")
  2. "ab" * 4
  3. "Hello" + " " + "there"
  4. "science"[3]
  5. "science"[0]
  6. len("")

Also: Write an f-string that displays a person's full name and age on one line. Define the variables first, then write the print statement.

Booleans

A Boolean (named after mathematician George Boole) is a value that is either True or False — exactly two values, nothing else. Booleans represent yes/no, on/off, and present/absent conditions. They are most often produced by comparison expressions.

Comparison Operators

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 5True
>Greater than5 > 10False
<=Less than or equal to5 <= 5True
>=Greater than or equal to3 >= 7False

Boolean Operators and Truth Tables

Three operators combine or modify Boolean values: and (True only if both sides are True), or (True if at least one side is True), and not (reverses the value).

ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue
Critical Distinction: = vs ==

= is assignment: stores a value into a variable. It is an instruction.
== is comparison: checks whether two values are equal and produces True or False.

Writing = when you mean == — or vice versa — causes bugs that can be difficult to find. This is one of the most common errors beginners make.

Practice 7.5Boolean Expressions
  1. 10 > 5
  2. 3 == 3.0
  3. 7 != 7
  4. True and False
  5. True or False
  6. not True
  7. 5 > 3 and 10 < 4
  8. 5 > 3 or 10 < 4
  9. not (5 == 5)
  10. not False or False
Sections 7.6 – 7.8
Expressions, Input and Output, and Type Conversion
Operator Precedence · print() and input() · int(), float(), str(), bool()

Expressions and Operators

An expression is any combination of values, variables, and operators that a program can evaluate to produce a single value. 3 + 4 evaluates to 7. score * 2 evaluates to twice the current value of score. age >= 18 evaluates to True or False. Every expression produces exactly one value, which can be stored, passed to a function, or used inside another expression.

Operator Precedence

When an expression contains multiple operators, evaluation follows precedence rules — similar to the order of operations in arithmetic. Higher-precedence operators evaluate first.

PriorityOperators
Highest** (exponentiation)
Unary - (negation)
*, /, //, %
+, -
Comparisons: <, >, <=, >=, ==, !=
not
and
Lowestor
When in Doubt, Use Parentheses

Parentheses are always evaluated first and make intent clear. (2 + 3) * 4 is unambiguous even if the reader does not know precedence rules. Parentheses also make code easier to read, which is just as important as making it correct.

Example 7.6.1
Precedence and parentheses
  • ProblemEvaluate 2 + 3 * 4 and (2 + 3) * 4. Explain why they differ.
  • Solve 2 + 3 * 4 → 2 + 12 → 14 (multiplication first) (2 + 3) * 4 → 5 * 4 → 20 (parentheses first)
14 and 20 — parentheses change the order of evaluation entirely.
Example 7.6.2
Compound expression with a discount
  • ProblemA product costs $49.99. A 10% discount is applied. Find the final price.
  • Solve discount = 0.10 original_price = 49.99 final_price = original_price * (1 - discount) # = 49.99 * (1 - 0.10) # = 49.99 * 0.90 # = 44.991
  • Check10% of 49.99 is about 5.00; 49.99 − 5.00 ≈ 44.99. ✓
final_price ≈ 44.991
Practice 7.6Expression Evaluation
  1. 5 + 3 * 2
  2. (5 + 3) * 2
  3. 2 ** 3 + 1
  4. 10 - 4 / 2
  5. 15 % 4 + 1
  6. 3 > 1 and 4 < 2
  7. not 5 == 5
  8. 3 > 1 or 4 < 2

Input and Output

Output: print()

The print() function displays output to the screen. It can take one value, multiple comma-separated values, or an f-string. By default, it separates multiple values with a space and ends with a newline.

print("Hello!")
print(42)
print(3.14)
print("Name:", name, "Age:", age)

Input: input()

The input() function pauses the program and waits for the user to type something. Whatever is typed is returned as a string — always a string, regardless of what the user typed. The argument to input() is the prompt shown to the user.

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

Converting Input to Numbers

Because input() always returns a string, you must convert the result if you need a number. If the user types 17, you receive the string "17" — you cannot do arithmetic on it directly without converting it first.

age = int(input("Enter your age: "))
next_year = age + 1
print(f"Next year you will be {next_year}")
Wrong Input Type

If the user types "seventeen" when the program expects an integer, int("seventeen") will fail with a ValueError. Handling this safely requires error handling techniques covered in later courses. For now, always ensure you convert input to the correct type before performing operations on it.

Practice 7.7Input and Output
  1. Write a program that asks the user for their name and prints a personalized greeting using an f-string.
  2. Write a program that asks for a temperature in Celsius and prints the converted Fahrenheit value. Formula: F = (C * 9/5) + 32. What conversion function do you need to apply to the input?
  3. A student writes age = input("Age: ") and then print(age + 1). What error will this produce and why?

Type Conversion

Type conversion (also called casting) changes a value from one type to another. Python provides built-in functions for the most common conversions.

FunctionConverts ToExampleResult
int()Integerint("42")42
float()Floatfloat("3.14")3.14
str()Stringstr(99)"99"
bool()Booleanbool(0)False

Note that int() applied to a float truncates — it removes the decimal portion without rounding. int(3.9) produces 3, not 4. int(-3.9) produces -3, not -4.

Falsy Values in Python

Every value has a Boolean interpretation. Falsy values — those that behave like False — include: 0, 0.0, "" (empty string), None, and empty collections. Everything else is truthy.

bool(0) → False    bool(1) → True    bool("") → False    bool("hi") → True

Example 7.8.1
Mixed type conversion in a calculation
  • Program price_text = "24.99" quantity_text = "3" price = float(price_text) quantity = int(quantity_text) total = price * quantity print(f"Total: ${total:.2f}")
  • Trace price = 24.99 (float) quantity = 3 (int) total = 24.99 * 3 = 74.97 :.2f rounds the display to 2 decimal places
Output: Total: $74.97
Practice 7.8Type Identification and Conversion

Part A: Identify the type of each value (int, float, str, or bool).

  1. 42
  2. "42"
  3. 3.14
  4. True
  5. "True"
  6. 0
  7. ""
  8. -7.5

Part B: What does each conversion produce?

  1. int(3.9)
  2. int(-3.9)
  3. float("7")
  4. str(100)
  5. bool(0)
  6. bool(-5)
  7. int("hello")
  8. bool("")
Sections 7.9 – 7.10
State, Changing Values, and Reading Programs
What State Means · Accumulators · Augmented Assignment · Reading Complete Programs

State and Changing Values

A program's state is the collection of all variables and their current values at any moment during execution. State changes as the program runs — variables are created, values are updated, and conditions shift. Understanding state is essential for reading programs and predicting output. When you trace a program, you are tracking its state step by step.

Example 7.9.1
Tracing state through a program
  • Program counter = 0 total = 0 counter = counter + 1 total = total + 10 counter = counter + 1 total = total + 15 print(counter) print(total)
  • Trace
    Statementcountertotal
    counter = 00—
    total = 000
    counter = counter + 110
    total = total + 10110
    counter = counter + 1210
    total = total + 15225
Output: 2  then  25

Accumulator Variables

An accumulator is a variable that builds up a value over time through repeated addition or other operations. The pattern total = total + value is so common that Python provides shorthand operators.

ShorthandEquivalentEffect
x += 5x = x + 5Add 5 to x
x -= 3x = x - 3Subtract 3 from x
x *= 2x = x * 2Multiply x by 2
x /= 4x = x / 4Divide x by 4
x //= 2x = x // 2Integer divide x by 2
x %= 3x = x % 3Replace x with x mod 3
score = 0
score += 10    # score is now 10
score += 25    # score is now 35
score -= 5     # score is now 30
print(score)   # 30

Swapping Two Variables

Swapping the values of two variables is a classic programming task. A naive approach fails because the first assignment overwrites the original value before the second assignment can read it. The correct approach uses a temporary variable to preserve the original value.

Example 7.9.2
Swapping with a temporary variable
  • Naive (wrong) a = 10 b = 20 a = b # a is now 20 — original value of a is LOST b = a # b is now 20, not 10 # Result: a = 20, b = 20 (WRONG)
  • Correct a = 10 b = 20 temp = a # save a's original value a = b # a gets b's value (20) b = temp # b gets original a's value (10) # Result: a = 20, b = 10 (CORRECT)
The temporary variable preserves the original value of a before it is overwritten.
Python One-Line Swap

Python allows a cleaner swap using tuple unpacking: a, b = b, a. This swaps the values in one line. The right side is fully evaluated before any assignment occurs, so neither value is lost. This is elegant Python — but the temporary variable method remains important to understand.

Practice 7.9State and Accumulators

Build a trace table and write the final output for each program.

  1. score = 0 / score += 10 / score += 25 / score -= 5 / score *= 2 / print(score)
  2. x = 8 / y = 3 / x, y = y, x / print(x) / print(y)
  3. A student runs this code to swap two values, but the result is wrong. Explain why it fails and write the corrected version:

    p = 5 / q = 9 / p = q / q = p / print(p, q)

Reading Simple Programs

A program is a list of instructions that execute from top to bottom, one at a time. Reading a program means following along and tracking what happens at each step. The habits of a good code reader: start at the top; for each line, ask what it does to the program's state; track variable values in a trace table; predict what each print() will produce before running the code. Do not run the code first — predict the output, then verify.

Example 7.10.1
A simple calculator program
print("Simple Calculator")
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))

total      = x + y
difference = x - y
product    = x * y

print(f"Sum:        {total}")
print(f"Difference: {difference}")
print(f"Product:    {product}")
  • ReadingPrint a header. Get two floats from the user. Compute three results. Print each using f-strings. Five variables: x, y, total, difference, product.
  • For x=6, y=4 Sum: 10.0 Difference: 2.0 Product: 24.0
Example 7.10.2
Name greeting with string operations
first = input("First name: ")
last  = input("Last name: ")
full_name = last + ", " + first
print(f"Hello, {full_name}!")
  • For "Alex" Rivera first = "Alex" last = "Rivera" full_name = "Rivera" + ", " + "Alex" = "Rivera, Alex" Output: Hello, Rivera, Alex!
Example 7.10.3
Temperature conversion with formula
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9 / 5) + 32
print(f"{celsius}°C = {fahrenheit}°F")
  • For celsius=100 100 * 9 = 900 900 / 5 = 180.0 180.0 + 32 = 212.0 Output: 100.0°C = 212.0°F
Practice 7.10Code Prediction

Predict the output of each program without running it. Then verify.

Program A:

a = 10
b = 4
c = a + b
a = c - a
print(a)
print(b)
print(c)

Program B:

score = 0
score += 10
score += 25
score -= 5
score *= 2
print(score)

Program C:

word = "science"
print(word[0])
print(len(word))
print(word[3])
print("cs " * 3)

Program D:

x = True
y = False
print(x and y)
print(x or y)
print(not x)
print(x and not y)

Chapter Summary

Key Terms Review

value
A piece of information a program can store and use: a number, a string, a Boolean, or other data.
variable
A named storage location in a program that holds a value and can be read or updated.
assignment
The process of storing a value into a variable using the = operator. The right side evaluates first.
integer (int)
A whole number with no decimal point, positive or negative. Used for counting and indexing.
float
A number with a decimal point, used for real-world measurements and calculations requiring fractions.
string (str)
A sequence of characters treated as text, enclosed in quotation marks.
Boolean (bool)
A data type with exactly two values: True and False. Named after mathematician George Boole.
data type
A classification that defines what kind of value a variable holds and what operations are valid on it.
expression
A combination of values, variables, and operators that evaluates to a single value.
operator precedence
Rules determining which operators in an expression are evaluated first when there are multiple operators.
concatenation
Joining two strings together using the + operator to produce a longer string.
index
A numeric position in a sequence, starting at zero in Python. Used to access individual characters or elements.
f-string
A formatted string literal prefixed with f, in which expressions inside {} are evaluated and inserted.
truth table
A table showing all possible input combinations for a Boolean operation and the resulting output.
type conversion
Changing a value from one data type to another, using functions like int(), float(), str(), or bool().
state
The complete collection of all variables and their current values at a given moment during program execution.
trace table
A table used to track variable values through each step of a program's execution, used to understand or debug a program.
accumulator
A variable that builds up a value over time, typically by repeatedly adding to it using the += pattern.
integer division (//)
Division that discards the decimal remainder and returns only the whole number portion.
remainder operator (%)
Returns what is left over after integer division. Also called the modulo operator. Useful for even/odd checks and time conversions.

Concept Check

Answer these questions to verify understanding before attempting practice problems.

  1. What is the difference between a value and a variable?
  2. What does the assignment operator = do? How is it different from the mathematical equals sign?
  3. What are the four basic data types introduced in this chapter?
  4. What does 7 // 3 produce? What does 7 % 3 produce?
  5. Why can you not add a string and an integer using + without conversion?
  6. What is the difference between = and ==?
  7. What does input() always return, regardless of what the user types?
  8. What is a trace table, and why is it useful?
  9. What does int(3.9) return? Does it round?
  10. What is the state of a program?

Skill Practice

Part AExpression Practice

Evaluate each expression and write the result.

  1. 5 + 3 * 2
  2. (5 + 3) * 2
  3. 10 // 3
  4. 10 % 3
  5. 2 ** 8
  6. 15 % 4
  7. 7 / 2
  8. 7 // 2
  9. True and False
  10. True or False
  11. not True
  12. 3 > 2 and 10 < 5
  13. 3 > 2 or 10 < 5
  14. not (5 == 5)
  15. len("computer")
Part BVariable Tracing

Construct a trace table for each program and write the output.

Program B1:

x = 4
y = 7
z = x + y
x = z - x
print(x)
print(y)
print(z)

Program B2:

a = 10
b = 3
a = a * b
b = a // b
print(a)
print(b)

Program B3:

count = 0
total = 0
count += 1
total += 50
count += 1
total += 30
count += 1
total += 70
print(count)
print(total)

Program B4:

word = "science"
first_letter = word[0]
length = len(word)
print(first_letter)
print(length)
print(word[3])

Design and Application Questions

For each question, define your variables clearly, write the program, and state what types you used and why.

  1. Write a program that asks the user for two numbers and prints their sum, difference, product, and integer quotient.
  2. Write a program that asks for a temperature in Fahrenheit and converts it to Celsius. Formula: C = (F - 32) * 5 / 9.
  3. A store charges a base price for an item and adds 8.5% sales tax. Write a program that asks for the base price and prints the tax amount and total price, both rounded to two decimal places.
  4. Write a program that asks for a person's first name, last name, and birth year. Print their full name (last, first format) and calculate approximately how old they are (use 2025 as the current year).
  5. Write a program that asks for the length and width of a rectangle and prints the area and perimeter.

Debugging and Error Analysis

Each program below contains a bug. Identify the error type (TypeError, ValueError, NameError, logic error), explain what is wrong, and write the corrected version.

Bug 1
score = 85
bonus = "10"
final_score = score + bonus
print(final_score)

What type error occurs? How do you fix it?

Bug 2
greeting = input("Name: ")
message = "Hello, " + greeting
length = len(message)
print("Length: " + length)

The last line will cause an error. What is wrong? How do you fix it?

Bug 3
radius = float(input("Enter radius: "))
pi = 3.14159
area = pi * radius ^ 2
print(area)

Python does not use ^ for exponentiation. What operator should be used? What does ^ actually do in Python?

Bug 4 — Logic Error
p = 5
q = 9
p = q
q = p
print(p, q)

The programmer intended to swap p and q. What does this code actually produce? Write the correct version using a temporary variable.

Bug 5
word = "hello"
print(word[5])

The string "hello" has 5 characters. Why does word[5] cause an error? What is the correct index for the last character?

Chapter 7 Checkpoint

Chapter 7 Checkpoint
Complete without assistance — assesses all key skills and concepts from Chapter 7
Section 1 — Vocabulary and Concepts
  1. Define variable and explain the three things a program can do with one (read, write, pass).
  2. Explain why x = x + 1 is valid in programming but impossible in mathematics.
  3. What is the difference between 7 / 2 and 7 // 2 in Python?
Section 2 — Expressions
  1. Evaluate: 3 + 4 * 2
  2. Evaluate: (3 + 4) * 2
  3. Evaluate: 17 % 5
  4. Evaluate: True and not False
  5. Evaluate: len("algorithm")
  6. Evaluate: int(7.9)
  7. Evaluate: bool("")
Section 3 — Variable Tracing
  1. Build a trace table and state the output: x = 5 / y = x * 2 / x = y - 3 / print(x) / print(y)
  2. A student writes: total = 0 / total += 15 / total += 30 / total *= 2 / total -= 10 / print(total) What is printed?
Section 4 — Types and Conversion
  1. Identify the type of each value: 99, "99", 99.0, False
  2. A student writes age = input("Age: ") and then print(age + 1). What error occurs? Write the corrected version.
  3. What is the difference between int(5.9) and rounding 5.9 to the nearest integer?
Section 5 — Design and Application
  1. Write a program that receives a number of seconds from the user and prints the equivalent minutes and remaining seconds using integer division and the remainder operator.
  2. Write a program that asks for a product's price and a discount percentage, and prints the discounted price. Use an f-string for the output. Define and name all variables clearly.

Real-World Applications

  1. Banking: A bank account program stores the current balance as a float. Every deposit adds to the balance; every withdrawal subtracts. Why should the balance be a float rather than an integer? What would happen if a programmer accidentally stored it as a string?
  2. Games: In a video game, a player has a score (int), a health level (float), a username (str), and an active status (bool). For each attribute, explain why that type is appropriate and give one example operation the game might perform on it.
  3. Temperature sensors: A weather station records temperatures as floats. Why is float more appropriate than integer for this data? What information would be lost if integers were used?
  4. Forms and databases: An online form collects a user's name, age, and email. The name is stored as a string, the age as an integer. Why is it wrong to store the age as a string even though the user types it as text?
  5. Calendars: A program receives a total number of days and needs to express it as weeks and remaining days. Write the expression using // and %. Test with 100 days.

Mixed Review

These questions draw on Chapters 1–7.

  1. What is binary representation, and why do computers use binary rather than decimal? (Chapter 4)
  2. A program needs to find the largest number in a list of 1,000 values. Before writing code, describe the algorithm in pseudocode. (Chapter 5)
  3. What is the difference between a syntax error and a logic error? Give an example of each in the context of Chapter 7 material. (Chapter 6)
  4. In Chapter 4, you learned that all digital information is stored as bits. Explain how a string like "hello" is ultimately represented in binary in a computer's memory. What role does text encoding (such as ASCII or Unicode) play?
  5. Why is abstraction (Chapter 3) relevant to the concept of a variable? What hardware detail does a variable hide from the programmer?
Looking Ahead
Chapter 8: Conditionals, Loops, and Control Flow

Chapter 7 gave programs the ability to store values, compute expressions, and track state. But programs so far can only execute instructions from top to bottom in a fixed order. Every program in this chapter ran straight through without making any decisions or repeating anything.

Chapter 8 introduces control flow — the mechanisms that let a program take different paths depending on conditions, and repeat actions as many times as needed. If statements ask whether a Boolean expression is true and branch accordingly. While loops repeat a block of code as long as a condition holds. For loops repeat over a sequence of values. The Boolean values and comparison expressions from this chapter become the deciding factor in every branch and every loop. By the end of Chapter 8, programs will be able to make decisions, repeat work efficiently, and process information in flexible ways that begin to resemble the software people use every day.

MGU Library Connection
  • Python Quick Reference — Appendix D of this textbook
  • Debugging and Testing Reference — Appendix E of this textbook
  • Chapter 6: Programming Languages and Code — syntax, semantics, and the Python environment
  • Chapter 8: Conditionals, Loops, and Control Flow — using Boolean expressions for decisions and repetition
  • Chapter 9: Functions, Decomposition, and Reuse — variables in function scope
  • Python Programming Foundations (MGU Computer Science Series) — extends all Chapter 7 concepts in depth