Mathew K Analytics

Lesson 1 · Pandas

02 Python Variables: Understanding and Using Variables in Python

In this lesson, we will explore how to use variables in Python. Variables let us store and reuse values so our code can work with information. You will…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Python Variables: The Building Blocks of Programs#

In this lesson, we will explore how to use variables in Python. Variables let us store and reuse values so our code can work with information.

You will practice creating, naming, and using variables with real examples!

import warnings
import numpy as np
np.random.seed(42)
warnings.filterwarnings("ignore")

# Let us start by assigning a value to a variable
x = 5
print(x)
5

What is a Variable?#

A variable is like a labeled box that stores a value. You can use the box over and over by giving it a name.

Think of a variable as a way to give data a name you can type and use later.

# Variable names can be almost anything: letters, numbers, and underscores.
user_name = "Alex"
favorite_color = "blue"
age = 28
print(user_name, favorite_color, age)
Alex blue 28

Syntax Basics: Naming Rules#

  • Names are case-sensitive (score is different from Score).
  • The first letter must be a letter or underscore.
  • Use only letters, numbers, and underscores.
  • No spaces or special characters allowed.

Tip: Pick clear names that explain what the variable stores.

# Case matters! These create two different variables.
height = 180
Height = 175
print(height)
print(Height)
180
175
# You cannot use spaces, but underscores are fine.
your_score = 90
# your score = 90  # This will give an error!
# Variable values can be changed any time.
points = 10
print("Points:", points)
points = 15
print("Points updated:", points)
Points: 10
Points updated: 15
# Store more than one value using multiple variables.
width = 5
height = 7
area = width * height
print("Area:", area)
Area: 35

Common Operations With Variables#

Variables help us store text, numbers, and more. You can use them in math, combine strings, and update their values.

Let us see some common things you can do with variables.

# Math with variables (addition, subtraction, etc.)
apples = 3
bananas = 4
total_fruit = apples + bananas
print("Total fruit:", total_fruit)
Total fruit: 7
# Combine text using + (called string concatenation)
first_name = "Taylor"
last_name = "Smith"
full_name = first_name + " " + last_name
print("Full Name:", full_name)
Full Name: Taylor Smith
# Update a variable based on its own value
counter = 1
counter = counter + 1
print(counter)
2
# Shorthand: += to add and assign at once.
x = 10
x += 5
print(x)
15

Types of Values Variables Can Hold#

Variables can store:

  • Numbers (integers, floats)
  • Text (strings)
  • True or False (boolean)

You can even combine different types in your program!

# Let us look at a few variable types.
score = 95           # integer
pi = 3.1416          # float (decimal number)
name = "Jordan"      # string (text)
is_active = True     # boolean
print(type(score), type(pi), type(name), type(is_active))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
# Variables change type as needed.
var = 123
print(type(var))
var = "Now I am a string!"
print(type(var))
<class 'int'>
<class 'str'>

User Input and Variables#

You can ask a user for data and store it in a variable with input().

This lets your code interact in real time.

# Save user data with input().
user_city = input("What city do you live in? ")
print("Hello to someone from", user_city)
Hello to someone from London
# Use input() for numbers too (string by default)
num_apples = input("How many apples do you want? ")
print("Type of num_apples:", type(num_apples))
num_apples = int(num_apples)
print("Now it is a number:", type(num_apples))
Type of num_apples: <class 'str'>
Now it is a number: <class 'int'>

Real-World Example: Storing User Profile Details#

Variables let you build personalized apps and games.

You might ask for a name, favorite animal, and age!

Let us do that now.

name = input("What is your name? ")
animal = input("Favorite animal? ")
age = input("How old are you? ")
print("Hi", name + ". You love", animal, "and are", age, "years old!")
Hi Jamie. You love dog and are 21 years old!
# Example: swap values between two variables
a = 3
b = 6
a, b = b, a
print("a:", a, "b:", b)
a: 6 b: 3

Related: The del Statement#

You can remove a variable with the del keyword.

This tells Python to forget that variable (it cannot be used after).

# Delete a variable
x = 22
del x
# print(x)  # This would give an error!

Mini-Project: Shopping Cart Total#

Let us use everything we learned to build a simple shopping cart. You will ask for item prices, add them up, and print a total.

Try typing your answers, then see your custom total!

item1 = float(input("Enter price of first item: "))
item2 = float(input("Enter price of second item: "))
item3 = float(input("Enter price of third item: "))
total = item1 + item2 + item3
print("Your total is:", total)
Your total is: 9.75
# Challenge: Try changing just one number to see how the total changes!
item1 = float(input("Try a new price for item1: "))
total = item1 + item2 + item3
print("New total:", total)
New total: 16.25

Variable Scope: Where Do Variables Live?#

Not all variables last forever or can be seen everywhere. Variables defined inside a function exist only in that function.

Let us see scope in action.

def show_scope():
    secret = "hidden"
    print("Inside:", secret)

show_scope()
# print(secret)  # This will fail!
Inside: hidden

Best Practices for Variables#

  1. Give meaningful names: user_score is better than us.
  2. Be consistent with case and style.
  3. Change variable values only when needed.
  4. Reuse variables carefully to avoid confusion.

Next up, let us review some common mistakes.

# Mistake: Reusing names with different meanings.
score = 50
score = "fifty points"
print(score)
fifty points
# Mistake: Typos in names silently create new variables.
favorite_color = "blue"
favourite_color = "red"
print(favorite_color, favourite_color)
blue red

Try It Yourself: Quick Practice#

  1. Make a variable called pet and set it to your favorite pet.
  2. Print out "My favorite pet is ___" using your variable.
# Your turn! Follow the instructions above.
pet = input("What is your favorite pet? ")
print("My favorite pet is", pet)
My favorite pet is parrot

Challenge: Make Your Own Welcome Message#

  1. Create a variable for a guest's name.
  2. Print a welcome message using the name.

Bonus: Ask the user for input first!

# Try this mini challenge.
guest_name = input("Enter your name: ")
print("Welcome,", guest_name, "!")
Welcome, Morgan !
# Advanced: Variables in f-strings for formatted output.
city = "Paris"
days = 7
print(f"Trip to {city} for {days} days!")
Trip to Paris for 7 days!
# Extra: Variables work in calculations and comparisons.
distance = 100
speed = 50
time = distance / speed
print("Travel time (hours):", time)
Travel time (hours): 2.0

Recap: What You Learned#

You now know how to:

  • Make variables for all kinds of data
  • Choose clear names and follow rules
  • Update or use variables in math and text
  • Handle input and output
  • Avoid common mistakes

Practice makes perfect!

If you liked this lesson, subscribe for more beginner-friendly Python videos!#

Comment your favorite variable name below!

Keep coding and see you in the next video!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.