Lesson 2 of 8

Variables and Data Types

Learn how to store and work with different types of data in Python

Learning Objectives

  • Understand what variables are and how to create them
  • Learn about different data types (strings, numbers, booleans)
  • Practice naming variables properly
  • Use variables in simple programs

What are Variables?

Think of variables as labeled boxes where you can store information. Just like you might put toys in a box labeled "Toys" or books in a box labeled "Books", variables let you store data with a name so you can use it later.

Creating Your First Variable:

# Creating variables is easy!
name = "Alex"
age = 12
favorite_color = "blue"

print("My name is", name)
print("I am", age, "years old")
print("My favorite color is", favorite_color)

Different Types of Data

Python can work with different types of information. Here are the main types you'll use:

Strings (Text)

Words, sentences, or any text

name = "Python"
message = "Hello World!"
letter = "A"

Numbers

Whole numbers or decimals

age = 12
height = 5.5
score = 100

Booleans

True or False values

is_student = True
likes_pizza = False
is_raining = True

Rules for Naming Variables

Good Variable Names

student_name = "Sarah"
favorite_number = 7
is_homework_done = True
player_score = 250
  • • Use descriptive names
  • • Use underscores for spaces
  • • Start with letters

Avoid These Names

x = "Sarah"        # Not descriptive
2name = "Bob"      # Can't start with number
my-age = 12        # No dashes allowed
class = "Math"     # Reserved word
  • • Too short or unclear
  • • Starting with numbers
  • • Using special characters

Practice Exercise

Create Your Own Variables

Try creating variables to store information about yourself. Copy this code into Spyder and fill in your own information:

# Fill in your information
my_name = "Your Name Here"
my_age = 0  # Put your age
favorite_subject = "Your Favorite Subject"
has_pet = True  # Change to False if you don't have a pet
favorite_number = 0  # Pick any number

# Print your information
print("Hi! My name is", my_name)
print("I am", my_age, "years old")
print("My favorite subject is", favorite_subject)
print("Do I have a pet?", has_pet)
print("My favorite number is", favorite_number)

Fun Challenge

Variable Math

Variables can do math too! Try this:

# Math with variables
apples = 5
oranges = 3
total_fruit = apples + oranges

print("I have", apples, "apples")
print("I have", oranges, "oranges")
print("Total fruit:", total_fruit)

# Try changing the numbers and see what happens!