Python Course
Variables in Python
Every program you have ever used stores information somewhere. When you log into a website, your username is stored. When you shop online, the price and quantity are stored. When you play a game, your score is stored. In Python, all of this is done using variables.
A variable is simply a name that points to a value stored in the computer's memory. You give it a name, put a value inside it, and then use that name whenever you need the value again. Think of it like a labeled box — you write a label on the outside and place something inside.
Variables are one of the most fundamental concepts in programming. Once you understand how they work, writing Python programs becomes much easier and more natural.
Creating a Variable in Python
In Python, creating a variable is very simple. You just write the name you want, followed by an equals sign, followed by the value you want to store. There is no need to declare a type or use any special keyword.
# Creating variables
x = 10 # stores a whole number
name = "Dataplexa" # stores text
price = 499.99 # stores a decimal number
Breaking Down Each Line
x = 10— creates a variable calledxand stores the number 10 inside it.name = "Dataplexa"— creates a variable callednameand stores the word Dataplexa.price = 499.99— creates a variable calledpriceand stores a decimal number.- The
=sign does not mean "equal to" here — it means "put this value into this variable". - Python figures out the type of data automatically. You do not need to say "this is a number" or "this is text".
Displaying a Variable on Screen
When you create a variable, the value is saved in memory but nothing appears on the screen. To see the value, you need to use the print() function.
x = 10
name = "Dataplexa"
print(x) # shows the number
print(name) # shows the text
print()takes whatever is inside the brackets and displays it on the screen.- You can print a variable directly by putting its name inside the brackets.
- Without
print(), the value stays in memory and you will not see it.
Changing a Variable's Value
Variables are not fixed. You can change the value stored inside a variable at any time. Python simply replaces the old value with the new one.
x = 10 # x now holds 10
x = 20 # x now holds 20
print(x)
- The original value 10 is gone. Python only keeps the most recent value.
- This is useful when you need to update information, like updating a score or a price.
Dynamic Typing in Python
In some programming languages, once you say a variable stores a number, it can only ever store a number. Python works differently. In Python, a variable can hold any type of value, and you can change that type at any time. This is called dynamic typing.
value = 100 # starts as a number
value = "Hello" # now it holds text
value = 3.14 # now it holds a decimal
print(type(value)) # shows the current type
- The
type()function tells you what kind of data a variable currently holds. - Python detects the type automatically based on the value you assign.
- Dynamic typing makes Python flexible and easier to use, especially when you are starting out.
Assigning Multiple Variables at Once
Python lets you create multiple variables in a single line. This is a clean and efficient way to set up several related values together.
# Assign three variables in one line
a, b, c = 10, 20, 30
print(a, b, c)
- The values are matched from left to right —
agets 10,bgets 20,cgets 30. - The number of variable names must match the number of values.
- This is useful when you want to set up several starting values at the same time.
Swapping Two Variables
Swapping means exchanging the values of two variables. In many languages this requires a temporary third variable. Python makes this much simpler.
x = 5
y = 10
# Swap in one line
x, y = y, x
print(x, y)
- Python handles the swap automatically without needing a third temporary variable.
- This is a feature unique to Python and makes certain types of code much cleaner.
Real World Example — Building a Billing System
Here is a practical example that brings variables together in a way that mirrors what real programs do every day. This code calculates the total cost of a purchase including tax.
# Product information
item_price = 799 # price of one item
quantity = 2 # number of items
tax_rate = 0.18 # 18% tax
# Calculations
subtotal = item_price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
# Show results
print("Subtotal:", subtotal)
print("Tax:", tax)
print("Total:", total)
How Each Variable Contributes
item_priceholds the cost of one item.quantityholds how many items were bought.subtotalis calculated by multiplying price by quantity.taxis calculated as 18% of the subtotal.totaladds the subtotal and tax together.- Each variable builds on the previous ones, making the code easy to read and modify.
Rules for Naming Variables
Python has a few rules about what you can and cannot name a variable. Breaking these rules will cause an error.
- Variable names can only contain letters, numbers, and underscores (
_). - A variable name cannot start with a number.
name1is valid.1nameis not. - Variable names are case sensitive.
scoreandScoreare two different variables. - You cannot use Python reserved words as variable names. Words like
print,if,for, andwhileare reserved. - Use underscores to separate words in long names:
item_price,total_amount,user_name.
Types of Data a Variable Can Store
A variable in Python can hold many different kinds of data. Here is a summary of the most common types you will use in this course:
| Type | Example | What It Stores |
|---|---|---|
| Integer (int) | age = 25 |
Whole numbers like 1, 50, 1000 |
| Float | price = 99.99 |
Decimal numbers like 3.14, 0.5 |
| String (str) | name = "Python" |
Text values in quotes |
| Boolean (bool) | is_active = True |
True or False only |
| List | numbers = [1, 2, 3] |
Multiple values in one variable |
| Dictionary | user = {"name": "Alex"} |
Key and value pairs |
Each of these types will be covered in detail in the lessons ahead. For now, the most important thing is knowing that variables can hold all of them.
Common Variable Mistakes and How to Avoid Them
These are the mistakes beginners make most often when working with variables:
- Using a variable before creating it — You must assign a value to a variable before you try to use it. Using an undefined variable causes a
NameError. - Misspelling a variable name — Python treats
usernameanduser_nameas two completely different variables. Be consistent. - Confusing = with == — A single
=stores a value. A double==checks if two values are equal. These are very different operations. - Starting a name with a number —
1score = 10will cause a syntax error. Always start names with a letter or underscore. - Using spaces in variable names —
item price = 10is not valid. Use underscores instead:item_price = 10.
Variables in Everyday Programs
To understand why variables matter, think about the apps and websites you use every day:
- A food delivery app stores your address, order total, and delivery time in variables.
- A music app stores the current song name, artist, and how far through the song you are.
- A banking app stores your balance, recent transactions, and account number.
- A social media platform stores your username, number of followers, and the posts you have liked.
Every piece of information in every program is stored in a variable at some point. Learning to work with variables well is one of the most valuable skills you can build as a programmer.
Practice
Variables store values in what part of the computer?
Quick Quiz
Python automatically detecting the type of a variable is called what?
Which function do you use to display the value of a variable on the screen?