Lesson 4 - Variables
Variables in Python
Variable is a storage container that stores a string or a number for you.
print("Hello world!")
print(text)
print(age)
You can specify a variable by giving it a name and assigning it a value. A variable's name needs to start with an alphabetic character, and it can be as short as one character, or as long as you like.
Variable Operations
Only the operators corresponding to a variable's type are allowed for that variable.
s = 20
print(s - 10)
s = "20"
print(s - 20)
name = "Bob"
print("Hello " + name)
You can assign variables with the values of other variables
greeting = "Hello " + name
print(greeting)
score = score + 50
print(score)
i,j = j,i
print(i,j)
Store Your Name
print("Hello", name)
🎯 Change "Alice" to your own name.
Favorite Number
print("My favorite number is", favorite)
🎯 Change the number.
Add Two Variables
b = 3
print(a + b)
💡 What if you change a and b?
Swap the Values
y = 20
x, y = y, x
print(x, y)
🎯 Predict what prints before running.
Combine Strings
second = "Morning"
print(first + " " + second)
💡 Try "Happy" + "Birthday".
Change After Assigning
print("Now:", age)
age = age + 1
print("Next year:", age)
🎯 What happens if you change 8?
Use One Variable in Many Places
print("The sky is", color)
print("The ocean is", color)
💡 Try a different color.
Calculate with Variables
height = 4
area = width * height
print("Area =", area)
🎯 Try other width and height.
Funny Sentences
food = "fish"
print("The", animal, "likes to eat", food)
💡 Change the words to make a silly sentence.
Reuse Variable
print(number)
number = number * 2
print(number)
🎯 What happens if you run it again?