Introduction to Python Programming

Andrew J. Pounds, Ph.D.

📝 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 You'll Learn:
  • 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 = 3

Now the variables numberOne and numberTwo can be used in further assignment statements:

numberTwo = numberOne + numberTwo

The variable numberTwo now contains the value of 5.

✓ Key Rule: In an assignment statement, there is always ONE variable on the left side of the = 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

  1. Open Spyder
  2. Click File → New File
  3. Type the code above
  4. Save it as assignment_1.py
  5. Press F5 to run

Sample Output:

numberOne = 2 numberTwo = 3

🔢 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:

numberOne = 2 numberTwo = 3 2 + 3 = 5
What Happened: The variable 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:

Initial values: numberOne = 2 numberTwo = 3 After reassignment: numberOne = 2 numberTwo = 5

🎯 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:

Boy True 3.14159 2
💡 Pro Tip: Unlike many languages, Python makes some assumptions about what the programmer wants to do. This flexibility is powerful but requires careful attention to data types!

➕ 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:

5.14159

But This Causes an Error:

flag = 2 + "Boy"

Error Message:

Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str'
⚠️ Important: You cannot mix numeric types with string types using the + 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:

3

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:

3

The boolean False is converted to "0" before it is used in the expression. The resulting expression is calculated and displayed.

⚠️ Be Careful! Python automatically converts 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
💡 Why Use Shorthand? Because of this behavior, the novice programmer has to be particularly careful when using reassignment. These shorthand operators make it clear what you're doing and reduce the chance of errors!

🏦 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:

Initial balance: $1000 After deposit of $250: $1250 After withdrawal of $100: $1150 After 2% interest: $1173.0 Final balance: $1173.0

❌ Common Mistakes and Solutions

Mistake 1: Putting the Variable on the Right

❌ Wrong:
2 + 3 = result # ERROR! Variable must be on the LEFT
✅ Correct:
result = 2 + 3

Mistake 2: Using a Variable Before Assigning It

❌ Wrong:
result = x + 5 # ERROR! x doesn't exist yet
✅ Correct:
x = 3 result = x + 5

Mistake 3: Mixing Strings and Numbers

❌ Wrong:
age = 25 message = "I am " + age + " years old" # ERROR!
✅ Correct:
age = 25 message = "I am " + str(age) + " years old"

Mistake 4: Forgetting That Variables Change

Common Confusion:
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:

  1. Assigns a temperature in Fahrenheit to a variable (try 32, 68, or 212)
  2. Uses an assignment statement to convert it to Celsius: C = (F - 32) * 5 / 9
  3. Prints both temperatures with labels

Exercise 2: Inventory Management

Write a program that:

  1. Starts with an initial inventory count
  2. Adds some items using +=
  3. Removes some items using -=
  4. Prints the count after each operation

Exercise 3: Calculate Total Cost

Write a program that:

  1. Assigns a unit price to a variable
  2. Assigns a quantity to a variable
  3. Calculates the total cost using an assignment statement
  4. Prints the unit price, quantity, and total in a formatted way

Exercise 4: Miles to Kilometers Converter

Write a program that:

  1. Assigns a distance in miles to a variable
  2. Converts it to kilometers: kilometers = miles * 1.60934
  3. Prints both distances with labels

Exercise 5: Grade Calculator

Write a program that:

  1. Assigns three test scores to variables
  2. Calculates the average using assignment: average = (score1 + score2 + score3) / 3
  3. Prints each score and the average

Exercise 6: Area and Perimeter Calculator

Write a program that:

  1. Assigns the length and width of a rectangle to variables
  2. Calculates the area: area = length * width
  3. Calculates the perimeter: perimeter = 2 * (length + width)
  4. 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:

  1. Read the error message—Python tells you what went wrong and where
  2. Verify variable names—spelling must be exact (is it numberOne or number_one?)
  3. Check data types—can you do that operation with those types?
  4. Print intermediate values—use print() to check what's in your variables
  5. Check the order—is the variable on the left and the expression on the right?
Remember: Every programmer encounters errors. Each one teaches you something new! The fact that you're working through these exercises means you're learning—even when (especially when!) you make mistakes.