Lesson 4 - Variables

Variables in Python

Variable is a storage container that stores a string or a number for you.

# Example without variable
print("Hello world!")
text = "Hello World!"
print(text)
age = 12
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.

# operator is allowed
s = 20
print(s - 10)
# code fails
s = "20"
print(s - 20)
# operator is allowed
name = "Bob"
print("Hello " + name)

You can assign variables with the values of other variables

name = "Bob"
greeting = "Hello " + name
print(greeting)
score = 100
score = score + 50
print(score)
i,j = 10,20
i,j = j,i
print(i,j)

Store Your Name

name = "Alice"
print("Hello", name)

🎯 Change "Alice" to your own name.

Favorite Number

favorite = 7
print("My favorite number is", favorite)

🎯 Change the number.

Add Two Variables

a = 5
b = 3
print(a + b)

💡 What if you change a and b?

Swap the Values

x = 10
y = 20
x, y = y, x
print(x, y)

🎯 Predict what prints before running.

Combine Strings

first = "Good"
second = "Morning"
print(first + " " + second)

💡 Try "Happy" + "Birthday".

Change After Assigning

age = 8
print("Now:", age)
age = age + 1
print("Next year:", age)

🎯 What happens if you change 8?

Use One Variable in Many Places

color = "blue"
print("The sky is", color)
print("The ocean is", color)

💡 Try a different color.

Calculate with Variables

width = 5
height = 4
area = width * height
print("Area =", area)

🎯 Try other width and height.

Funny Sentences

animal = "cat"
food = "fish"
print("The", animal, "likes to eat", food)

💡 Change the words to make a silly sentence.

Reuse Variable

number = 4
print(number)
number = number * 2
print(number)

🎯 What happens if you run it again?