0%

5- Variables in Python

A variable is a small magic box. You put a value inside, give it a name, and later you whisper that name to retrieve what you stored.

Imagine you are a wizard with many ingredients. You have a jar of moon dust, a bottle of morning dew, and a pouch of silver sparks. You could carry them all in your hands, but that would be chaos. Instead, you label each container. “Moon dust.” “Morning dew.” “Silver sparks.” When you need moon dust, you simply reach for the jar with that label. Variables in Python work exactly like these labeled jars. They are named containers that hold values. You create a variable by choosing a name and using the equals sign to put something inside it. Every variable has three things: a name (what you call it), a value (what it holds), and a type (what kind of data it is). Python figures out the type automatically from the value you put inside.

🕯️ Magic Note

In many programming languages, you must declare a variable’s type before using it (like saying “this jar will only hold moon dust”). Python is different. You simply put a value inside, and Python remembers the type for you. This is called dynamic typing. It gives you freedom, but also responsibility. A variable can change its type if you put something new inside.

Creating Your First Variable
Creating a variable is called “assignment”. You use the equals sign = which means “take the value on the right and put it into the variable on the left”. The pattern is simple: variable_name = value

Python

# Creating variables (assignment)

age = 25

name = “Feloriya”

price = 19.99

is_magical = True

# Using variables (reading the value)

print(age) # 25

print(name) # Feloriya

print(price + 5) # 24.99

💡 Read the equals sign as “becomes” or “is assigned to”, not “equals”. x = 5 means “x becomes 5” or “assign 5 to x”. This is different from mathematics where = means equality.
Rules for Variable Names
Variable names are not free. Python has rules you must follow. Break them, and Python will raise an error before your spell even begins.
RuleExample (Valid)Example (Invalid)
Start with a letter or underscorename, _hidden1name (cannot start with number)
Can contain letters, numbers, underscoresuser_1, my_varuser-name (hyphen not allowed)
Case sensitiveage vs Age (different variables)N/A
Cannot use Python keywordsmy_classclass (reserved keyword)
No spaces allowedfirst_namefirst name (space not allowed)
Python keywords (also called reserved words) are words that Python uses for its own syntax. You cannot use them as variable names. Here are the most common ones you should avoid:
andasassertasyncawait
breakclasscontinuedefdel
elifelseexceptFalsefinally
forfromglobalifimport
inislambdaNonenonlocal
notorpassraisereturn
Truetrywhilewithyield

Python

# Valid variable names

user_age = 25

_private = “secret”

variable1 = 100

long_variable_name = “okay”

camelCaseIsAllowed = “but not common in Python”

# Invalid variable names (will cause SyntaxError)

# 1user = 10

# user-name = “Ali”

# class = “Python”

# my variable = 5

🕯️ Magic Note

Python has a style guide called PEP 8. It recommends using snake_case for variable names: all lowercase letters with underscores between words. Examples: user_age, first_name, total_price. This is not a rule (Python will accept other styles) but following it makes your code more readable to other Python programmers.

Reassigning Variables
Variables are not permanent. You can change what a variable holds at any time. Just assign a new value using the same name. The old value is forgotten (and eventually cleaned up by Python).

Python

score = 10

print(score) # 10

score = 25

print(score) # 25 (value changed)

score = “high” # Now score holds a string, not a number

print(score) # high (type changed too!)

⚠️ Reassigning a variable to a different type is allowed in Python but can be confusing. If score starts as a number and later becomes a string, any code that expects a number will break. It is better to keep each variable’s type consistent unless you have a very good reason to change it.
Multiple Assignments
Python allows you to assign values to multiple variables in one line. This is elegant, efficient, and very Pythonic.

Python

# Assign multiple variables at once

a, b, c = 1, 2, 3

print(a) # 1

print(b) # 2

print(c) # 3

# Assign the same value to multiple variables

x = y = z = 0

print(x, y, z) # 0 0 0

💡 Multiple assignment is especially useful for swapping values. In many languages, swapping two variables requires a temporary variable. In Python, you can do it in one elegant line: a, b = b, a.

Python

# Swapping values without a temporary variable

x = 5

y = 10

print(x, y) # 5 10

x, y = y, x # The magic swap

print(x, y) # 10 5

Variable Types Can Change (Dynamic Typing)
Python is dynamically typed. This means a variable can hold any type of value, and that type can change over time. Python checks the type when the code runs, not before. This is different from statically typed languages (like C, Java, or Rust) where you must declare a variable’s type and it never changes.

Python

data = 42 # data is an int

print(type(data)) # <class ‘int’>

data = “forty two” # now data is a str

print(type(data)) # <class ‘str’>

data = 3.14 # now data is a float

print(type(data)) # <class ‘float’>

🕯️ Magic Note

Dynamic typing gives you flexibility. You do not need to plan everything in advance. You can write code that adapts to different situations. However, with great power comes great responsibility. Changing a variable’s type midway through your program can lead to bugs that are hard to find. Use this freedom wisely.

Variable Naming Conventions (Best Practices)
Beyond the rules, there are conventions. These are not enforced by Python, but good programmers follow them to make code readable.
ConventionExampleWhen to Use
snake_caseuser_age, total_priceRegular variables (recommended)
UPPER_CASEMAX_SIZE, PIConstants (values that never change)
_single_underscore_internal“Private” variable (internal use only)
__double_underscore__privateName mangling (advanced, for classes)

Python

# Constants in Python (by convention only)

MAX_CONNECTIONS = 100

DEFAULT_COLOR = “#000000”

PI = 3.14159

# Python does not prevent changing these

# But other programmers will know they should stay constant

Deleting Variables
When you no longer need a variable, you can delete it using the del statement. After deletion, trying to use the variable will cause a NameError.

Python

temp_value = 100

print(temp_value) # 100

del temp_value

# print(temp_value) # NameError: name ‘temp_value’ is not defined

💡 You rarely need to use del manually. Python automatically cleans up variables when they go out of scope (for example, when a function ends). del is useful when you want to explicitly remove a variable to free memory or avoid accidental reuse.
The Role of Variables in Programs
Variables are everywhere. They store user input, keep track of scores, hold configuration settings, and remember the state of your program. Here is a small example that combines many concepts:

Python

# A small spell that uses variables

user_name = input(“Enter your name: “)

birth_year = int(input(“Enter your birth year: “))

current_year = 2025

age = current_year – birth_year

print(f”Hello {user_name}!”)

print(f”You are approximately {age} years old.”)

# Possible output:

# Hello Feloriya!

# You are approximately 25 years old.

Common Mistakes with Variables
  • Using a variable before assigning a value to it: print(score) before score = 10 causes NameError
  • Forgetting that Python is case sensitive: Name and name are different variables
  • Using reserved keywords: class = “Python” causes SyntaxError
  • Putting spaces in variable names: user name = “Ali” is invalid
  • Starting a variable name with a number: 1st_place = “gold” is invalid
  • Confusing = (assignment) with == (equality comparison)
  • Assuming a variable keeps its type forever (dynamic typing means it can change)
⚠️ The most common beginner mistake is trying to use a variable that has not been defined yet. Always assign a value to a variable before you try to read from it. Python reads your code from top to bottom, so variable definitions must come before their use.
Check Your Understanding
  • How do you create a variable named score with the value 100?
  • Which of these is a valid variable name: 2cool, cool_2, cool-2, class?
  • What happens if you try to use a variable before assigning it a value?
  • Write one line of code that swaps the values of a and b.
  • Can a variable change its type after being created? Give an example.
  • What does PEP 8 recommend for variable naming?

⚡ Whisper

A variable is a whisper you write down so you do not forget. You give it a name that means something to you, and you place a value inside. Later, when you speak that name, the value returns to you as if it never left. This is the simplest form of memory. This is where all programs begin. A name. A value. A quiet understanding between you and the machine. Guard your names well. Choose them with care. A spell cast with a confusing name is a spell that will fail when you need it most.

Related posts