Learn how to store and work with different types of data in Python
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 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) Python can work with different types of information. Here are the main types you'll use:
Words, sentences, or any text
name = "Python"
message = "Hello World!"
letter = "A" Whole numbers or decimals
age = 12
height = 5.5
score = 100 True or False values
is_student = True
likes_pizza = False
is_raining = True student_name = "Sarah"
favorite_number = 7
is_homework_done = True
player_score = 250 x = "Sarah" # Not descriptive
2name = "Bob" # Can't start with number
my-age = 12 # No dashes allowed
class = "Math" # Reserved word 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) 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!