📝 Exercise Two: Assignment Statements
In Exercise One, you learned how to get input from users and display output. Now we're going to explore assignment statements—one of the most fundamental concepts in programming. Assignment statements let you store, retrieve, and manipulate data in your programs.
- What assignment statements are and how they work
- How to create and use variables
- How variables can be reassigned to new values
- How to use variables in mathematical expressions
- Important rules about mixing data types
- Shorthand operators for faster coding
❓ What is an Assignment Statement?
The simplest form of an assignment statement assigns a value to a named variable. For instance, in the example below, the value of "2" is assigned to a variable named numberOne and the value of "3" is assigned to a variable named numberTwo:
numberOne = 2
numberTwo = 3Now the variables numberOne and numberTwo can be used in further assignment statements:
numberTwo = numberOne + numberTwoThe variable numberTwo now contains the value of 5.
= sign and some form of mathematical or computable expression on the right side. The variable on the left assumes the type of the expression on the right. This could be a string, floating point number, integer, or boolean.
📊 Understanding Data Types
Python handles many different types of data, but most programs are written with three different types:
| Data Type | Description | Examples |
|---|---|---|
| Strings | A collection of characters like "ABC Bail Bonding". In the preceding string, there are actually sixteen characters as the spaces count as characters too. | "Hello", "ABC Bail Bonding", "Room 204" |
| Integers | Positive and negative counting numbers like -10, 0, 8, etc. | -10, 0, 42, 2024 |
| Floats | Floating point numbers are numbers with decimals. It should be recognized, however, that they are finite values. For example, the value of pi as a float is 3.1415926535897. It does not go on forever—it is truncated or rounded after a certain number of decimal places. | 3.14159, 98.6, -0.5 |
✏️ Example 1: Simple Assignment
Let's start with the most basic assignment statements:
numberOne = 2
numberTwo = 3
print("numberOne =", numberOne)
print("numberTwo =", numberTwo)Save and Run This Program
- Open Spyder
- Click File → New File
- Type the code above
- Save it as
assignment_1.py - Press F5 to run
Sample Output:
🔢 Example 2: Using Variables in Expressions
Now that we have variables with values, we can use them in mathematical expressions:
numberOne = 2
numberTwo = 3
result = numberOne + numberTwo
print("numberOne =", numberOne)
print("numberTwo =", numberTwo)
print(numberOne, "+", numberTwo, "=", result)Sample Output:
result now holds the value 5 (which is 2 + 3). When we assign an expression to a variable, Python calculates the right side first, then stores the result in the variable on the left.
🔄 Example 3: Reassigning Variables
Variables can be reassigned—you can change their value at any time. When you reassign a variable, it takes on the new value and forgets the old one:
numberOne = 2
numberTwo = 3
print("Initial values:")
print("numberOne =", numberOne)
print("numberTwo =", numberTwo)
numberTwo = numberOne + numberTwo
print()
print("After reassignment:")
print("numberOne =", numberOne)
print("numberTwo =", numberTwo)Sample Output:
🎯 Example 4: Variables Change Type
In Python, a variable can hold different types of data at different times. The variable takes on whatever type of value you assign to it:
flag = "Boy"
print(flag)
flag = True
print(flag)
flag = 3.14159
print(flag)
flag = 2
print(flag)Sample Output:
➕ Example 5: Combining Numeric Types
You can combine different numeric types (integers and floats) in assignment expressions, but you cannot mix numeric types with other types. For example:
flag = 2 + 3.14159
print(flag)Sample Output:
But This Causes an Error:
flag = 2 + "Boy"Error Message:
+ operator in assignment statements. You must convert one type to another first (as you learned in Exercise One).
🤔 Example 6: Strange Behavior - Booleans in Math
There is a strange thing that happens when you combine numeric types with boolean (True/False) types:
flag = 2 + True
print(flag)Output:
In the above example, the boolean True is converted to "1" before it is used in the expression. Similarly:
flag = flag + False
print(flag)Output:
The boolean False is converted to "0" before it is used in the expression. The resulting expression is calculated and displayed.
True to 1 and False to 0 in mathematical expressions. This can be confusing! As a beginner, try to avoid mixing Booleans with numbers unless you really mean to use this behavior.
⚡ Example 7: Shorthand Assignment Operators
Operations like A = A + B are so common in computer programming that Python allows statements like A += B to be used instead of A = A + B. This can make coding faster and easier, but because of this behavior the novice programmer has to be particularly careful. The other numeric operators (-, *, /) can be used in a similar manner:
| Shorthand | Equivalent To | Example |
|---|---|---|
A += B |
A = A + B |
count += 1 |
A -= B |
A = A - B |
count -= 1 |
A *= B |
A = A * B |
total *= 2 |
A /= B |
A = A / B |
total /= 2 |
🏦 Example 8: Real-World Application - Bank Account
Let's use assignment statements to simulate a bank account with deposits, withdrawals, and interest:
account_balance = 1000
print("Initial balance: $" + str(account_balance))
deposit = 250
account_balance += deposit
print("After deposit of $" + str(deposit) + ": $" + str(account_balance))
withdrawal = 100
account_balance -= withdrawal
print("After withdrawal of $" + str(withdrawal) + ": $" + str(account_balance))
interest_rate = 0.02
interest = account_balance * interest_rate
account_balance += interest
print("After 2% interest: $" + str(account_balance))
print()
print("Final balance: $" + str(account_balance))Sample Output:
❌ Common Mistakes and Solutions
Mistake 1: Putting the Variable on the Right
2 + 3 = result # ERROR! Variable must be on the LEFTresult = 2 + 3Mistake 2: Using a Variable Before Assigning It
result = x + 5 # ERROR! x doesn't exist yetx = 3
result = x + 5Mistake 3: Mixing Strings and Numbers
age = 25
message = "I am " + age + " years old" # ERROR!age = 25
message = "I am " + str(age) + " years old"Mistake 4: Forgetting That Variables Change
x = 5
x = x + 3
print(x) # Many beginners expect 5, but the answer is 8!What happened: After the second line, x is changed to 8. The original value of 5 is gone. This is expected Python behavior—not a mistake in your code, but a common misunderstanding!
✏️ Practice Exercises
Try writing these programs on your own! This is the best way to learn.
Exercise 1: Temperature Conversion
Write a program that:
- Assigns a temperature in Fahrenheit to a variable (try 32, 68, or 212)
- Uses an assignment statement to convert it to Celsius:
C = (F - 32) * 5 / 9 - Prints both temperatures with labels
Exercise 2: Inventory Management
Write a program that:
- Starts with an initial inventory count
- Adds some items using
+= - Removes some items using
-= - Prints the count after each operation
Exercise 3: Calculate Total Cost
Write a program that:
- Assigns a unit price to a variable
- Assigns a quantity to a variable
- Calculates the total cost using an assignment statement
- Prints the unit price, quantity, and total in a formatted way
Exercise 4: Miles to Kilometers Converter
Write a program that:
- Assigns a distance in miles to a variable
- Converts it to kilometers:
kilometers = miles * 1.60934 - Prints both distances with labels
Exercise 5: Grade Calculator
Write a program that:
- Assigns three test scores to variables
- Calculates the average using assignment:
average = (score1 + score2 + score3) / 3 - Prints each score and the average
Exercise 6: Area and Perimeter Calculator
Write a program that:
- Assigns the length and width of a rectangle to variables
- Calculates the area:
area = length * width - Calculates the perimeter:
perimeter = 2 * (length + width) - Prints both values with labels
📚 Quick Reference
| Operation | Syntax | Example |
|---|---|---|
| Basic assignment | variable = value |
x = 5 |
| Addition assignment | variable += value |
x += 3 |
| Subtraction assignment | variable -= value |
x -= 2 |
| Multiplication assignment | variable *= value |
x *= 4 |
| Division assignment | variable /= value |
x /= 2 |
⭐ Key Takeaways
- ✓ An assignment statement stores a value in a variable
- ✓ The variable always goes on the left of the
=sign - ✓ Variables take on the type of the value assigned to them
- ✓ You can reassign variables to new values at any time
- ✓ You can use variables in expressions on the right side
- ✓ Be careful mixing different data types—especially strings and numbers
- ✓ Use shorthand operators (
+=,-=, etc.) to write cleaner code - ✓ Python has strange behavior with Booleans in math—avoid mixing them unless needed
💬 Need Help?
If your program doesn't work, follow these steps:
- Read the error message—Python tells you what went wrong and where
- Verify variable names—spelling must be exact (is it
numberOneornumber_one?) - Check data types—can you do that operation with those types?
- Print intermediate values—use
print()to check what's in your variables - Check the order—is the variable on the left and the expression on the right?