Variables & Data Types

Variables & Data Types in Python: Imagine you are moving to a new house. You have boxes, and you label them: "Kitchen", "Books", "Clothes".

Imagine you are moving to a new house. You have boxes, and you label them: "Kitchen", "Books", "Clothes". In Python, variables are like those labels (or boxes). They store information that you can reference later.

Concept Explanation

A variable is essentially a named location in the computer's memory where you can store data. Rather than having to remember specific memory addresses, the computer allows you to assign a human-readable name (like age or username) to that data. When the program runs, it can look inside that specific "box" and retrieve the value inside of it, or even change the value entirely.

Because Python is "dynamically typed", you do not have to announce ahead of time what kind of data is going to be stored in the box. In rigid languages like Java, you must declare int score = 10; to lock the box to integers only. Python simplifies this down to just score = 10.


Syntax or Core Structure

Creating a Variable

You don't need to declare a type (like "this box is only for books"). Python figures it out.

Code Example #1 (Basic)

score = 10     # integer
name = "Alex"  # string
price = 19.99  # float

print(name)    # Will output: Alex
print(score)   # Will output: 10

Code Example #2 (Intermediate)

Variables can be assigned to the results of complex mathematical operations, or they can even be updated continuously as the program runs.

base_price = 50.00
tax_rate = 0.08
final_price = base_price + (base_price * tax_rate)

print("The final total is:")
print(final_price) # Outputs 54.0

# Reassigning variables (updating the box's contents)
lives_remaining = 3
lives_remaining = lives_remaining - 1 # Player loses a life
print("Lives left:", lives_remaining) # Outputs 2

Data Types

Although Python is dynamically typed, data still has a type.

  1. Integers (int): Whole numbers (e.g., 5, -10, 42).
  2. Floating Point (float): Decimals (e.g., 3.14, 0.001).
  3. Strings (str): Text (e.g., "Hello").
  4. Booleans (bool): Logic values (True or False).

Checking Types

You can check the type of any variable using type().

x = 100
print(type(x)) 
# Output: <class 'int'>

Naming Rules & Conventions

To keep your code clean, follow these rules:

  1. Snake Case: Use underscores for multi-word variables.
  • ✅ user_name
  • ✅ total_score
  • ❌ userName (CamelCase is usually for Classes)
  1. Case Sensitive: age, Age, and AGE are three different variables.
  1. No Numbers at Start:
  • ✅ player1
  • ❌ 1player (Syntax Error)

Type Casting

Sometimes you need to treat a number like text (string) or vice versa. This is called Casting.

Scenario: Concatenating Text and Numbers

This will cause an error:

age = 25
print("I am " + age + " years old") 
# TypeError: can only concatenate str (not "int") to str

The Fix: Convert to String

print("I am " + str(age) + " years old")

Common Casting Functions

  • int("10") -> 10
  • float(5) -> 5.0
  • str(100) -> "100"

Real World Example

In a banking application, you frequently need to manage customer balances, usernames, and transaction logic.

# Banking User Profile Profile
customer_name = "Sarah Jenkins"
is_premium_member = True
account_balance = 1250.75

print("Welcome, " + customer_name)
print("Are you a premium member?")
print(is_premium_member)

# Simulating a deposit
account_balance = account_balance + 200.00
print("New Balance: $" + str(account_balance))

Common Mistakes

  1. Using Reserved Keywords: You cannot name your variable a word that Python already uses for its syntax. Naming a variable print = 5 or True = 10 will break your program.
  2. Forgetting to Cast: Trying to add a number to a string, like "User" + 3. Python doesn't know if you want the string "User3" or if you're trying to do mathematical addition, so it throws a TypeError.
  3. Misspelling Variables: Variables are case-sensitive. If you declare maxHealth = 100, and then try to lower it with maxhealth = maxhealth - 10, the code will crash because maxhealth is undefined.

Best Practices

  • Descriptive Naming: Always name variables after what they actually represent. user_age = 25 is vastly superior to x = 25. It makes your code self-documenting.
  • Avoid Single Letter Variables: Unless you are creating a quick mathematical loop (like x and y coordinates), avoid single letter names. You will forget what a or b stood for two weeks from now.

Practice Exercises

  1. Declare Variables: Create three variables: a string containing your favorite color, an integer with your birth year, and a float representing the exact price of a cup of coffee. Print all three.
  2. Math with Variables: Create a variable called length and set it to 10. Create width and set it to 5. Calculate the area (length * width) and store it in a new variable, then print the result.
  3. Type Checking: Assign the value "42" (with quotes) to a variable. Use the type() function to print its current type, then cast it to an integer and print the mathematical result of adding 10 to it.
  4. Fix the Naming: The variable 1st_player_score = 100 is invalid. Fix the name so it follows the correct snake_case and numbering rules, then print it.
  5. The Casting Fix: Try to print "I have " + 5 + " apples." Python will throw an error. Use casting to fix the code and make it run successfully.