Python Variables — Complete Beginner's Reference
What variables are, how to create them, assign values, naming rules, types, scope, and much more
■ What is a Variable?
A variable is a named container that stores a value in your computer's memory. Think of it like a labelled box — you give the box a name, put
something inside it, and later you can open it to use what's inside or replace it with something new.
In Python, you do not need to declare a variable before using it. Just assign a value and Python creates it automatically.
Real-life analogy:
Imagine a box labelled name. You put 'Zia' inside it. Later your program opens that box and reads 'Zia'. If you want, you can replace 'Zia' with
'Ahmed'. The box (variable) stays the same — only its contents change.
name = 'Zia' # box called 'name' contains 'Zia'
age = 25 # box called 'age' contains 25
print(name)
print(age)
>> Zia
>> 25
■ Python variables are created the moment you assign a value to them. No special keyword like 'var' or 'int' needed.
01 Creating and Assigning a Variable — The = Operator
The single equals sign = is the assignment operator. It does NOT mean 'equal to' like in maths — it means 'store this value into this variable'.
The variable name is always on the LEFT, the value is always on the RIGHT.
Syntax:
variable_name = value
Examples:
name = 'Zia'
age = 25
height = 5.9
is_student = True
score = 0
print(name)
print(age)
print(height)
print(is_student)
>> Zia
>> 25
>> 5.9
>> True
■ = is assignment (store a value). == is comparison (are two things equal?). Never confuse these two.
02 Variable Naming Rules — What is Allowed
Python has strict rules for naming variables. Breaking these rules gives a SyntaxError.
MUST follow these rules:
Rule 1 — Can only contain letters (a-z, A-Z), digits (0-9), and underscore (_)
Rule 2 — Must START with a letter or underscore. Cannot start with a digit.
Rule 3 — Cannot be a Python keyword (like if, for, while, print, True, etc.)
Rule 4 — No spaces allowed. Use underscore _ to separate words.
Rule 5 — Case sensitive: name, Name, and NAME are three different variables.
Valid names — these work:
name = 'Zia'
first_name = 'Zia'
_hidden = 99
totalMarks = 450
marks2024 = 88
MAX_SIZE = 100
Invalid names — these cause errors:
2name = 'Zia' # SyntaxError: cannot start with digit
first-name = 'Zia' # SyntaxError: hyphen not allowed
my name = 'Zia' # SyntaxError: space not allowed
for = 10 # SyntaxError: 'for' is a keyword
class = 9 # SyntaxError: 'class' is a keyword
■ Python keywords (reserved words) you cannot use as variable names: False, None, True, and, as, assert, async, await, break, class, continue,
def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
03 Naming Conventions — Best Practices
Rules tell you what Python ALLOWS. Conventions tell you what professional programmers PREFER. Following conventions makes your code
readable and professional.
snake_case — most common for variables and functions:
All lowercase, words separated by underscores. This is the standard Python style (PEP 8).
first_name = 'Zia'
total_marks = 450
is_student = True
phone_number = '0300-1234567'
UPPER_SNAKE_CASE — for constants (values that never change):
MAX_STUDENTS = 40
PI = 3.14159
SCHOOL_NAME = 'Leeds School'
camelCase — used in some older Python code (not recommended for variables):
firstName = 'Zia' # valid but not preferred
totalMarks = 450 # valid but not preferred
Meaningful names — always use descriptive names:
x = 25 # bad: what does x mean?
a = 'Zia' # bad: what is 'a'?
age = 25 # good: clear and obvious
student_name = 'Zia' # good: very clear
✓ Good variable names make code readable even without comments. Always name variables for what they contain.
04 Data Types — What You Can Store in a Variable
Python variables can hold many different types of data. Python figures out the type automatically from the value you assign — you never need to
declare the type yourself. This is called dynamic typing.
Type Name Keyword Example Value Code Example
Integer int 25, -10, 0 age = 25
Float float 3.14, -9.5, 0.0 height = 5.9
String str 'Zia', "Hello" name = 'Zia'
Boolean bool True, False is_student = True
None NoneType None result = None
List list [1, 2, 3] marks = [85, 90, 78]
Tuple tuple (1, 2, 3) coords = (33.6, 70.9)
Dictionary dict {'key': value} student = {'name':'Zia'}
Set set {1, 2, 3} unique = {1, 2, 3}
Checking the type of a variable — type():
name = 'Zia'
age = 25
gpa = 3.8
flag = True
print(type(name))
print(type(age))
print(type(gpa))
print(type(flag))
>>
>>
>>
>>
05 Assigning Different Types — With Full Examples
String (str) — text data:
Any text wrapped in single or double quotes. Can contain letters, numbers, spaces, symbols.
first_name = 'Zia'
last_name = "Ahmed"
city = 'DI Khan'
sentence = 'Python is easy to learn.'
mixed = 'Room 101, Block B'
empty = "" # empty string is valid
Integer (int) — whole numbers:
age = 25
roll_number = 101
year = 2026
negative = -50
zero = 0
big_number = 1_000_000 # underscore allowed for readability
>> 1000000
Float (float) — decimal numbers:
height = 5.9
weight = 68.5
pi = 3.14159
temperature = -2.5
percentage = 98.75
Boolean (bool) — True or False only:
is_student = True
has_passed = False
is_logged_in = True
is_empty = False
# Booleans come from comparisons too:
print(10 > 5) # True
print(3 == 7) # False
print(5 != 3) # True
None — represents no value / empty / unknown:
result = None
middle_name = None # person has no middle name
print(result)
>> None
06 Reassigning a Variable — Changing Its Value
Variables are called 'variable' for a reason — their value CAN change. You can reassign a variable as many times as you want. The old value is
simply replaced.
score = 0
print(score)
score = 50
print(score)
score = 100
print(score)
>> 0
>> 50
>> 100
You can even change the type when reassigning:
x = 10 # x is an integer
print(type(x))
x = 'hello' # now x is a string
print(type(x))
x = 3.14 # now x is a float
print(type(x))
>>
>>
>>
■ Python allows changing types freely. This is called dynamic typing. Most other languages (C, Java) do NOT allow this.
07 Multiple Assignment — Assigning Several Variables at Once
Python lets you assign values to multiple variables in a single line. This makes code shorter and cleaner.
Assign different values to different variables:
name, age, city = 'Zia', 25, 'DI Khan'
print(name)
print(age)
print(city)
>> Zia
>> 25
>> DI Khan
Assign the same value to multiple variables:
a = b = c = 0
print(a, b, c)
>> 0 0 0
Swap two variables in one line:
x = 10
y = 20
x, y = y, x # swap without a temp variable!
print(x, y)
>> 20 10
Unpack a list into variables:
marks = [85, 90, 78]
english, maths, science = marks
print(f'English: {english}, Maths: {maths}, Science: {science}')
>> English: 85, Maths: 90, Science: 78
✓ The swap trick x, y = y, x is very Pythonic. In other languages you need a temporary variable to do this.
08 Augmented Assignment Operators
Instead of writing x = x + 5, Python gives you shorthand operators that update a variable in place. These are called augmented assignment
operators.
Operator Meaning Example Same As
+= Add and assign x += 5 x = x + 5
-= Subtract and assign x -= 3 x = x - 3
*= Multiply and assign x *= 2 x = x * 2
/= Divide and assign x /= 4 x = x / 4
//= Floor divide & assign x //= 3 x = x // 3
%= Modulus and assign x %= 2 x = x % 2
**= Power and assign x **= 3 x = x ** 3
Practical example — counting score:
score = 0
score += 10 # got 10 marks
print(score)
score += 25 # got 25 more
print(score)
score -= 5 # penalty 5 marks
print(score)
score *= 2 # doubled (bonus round)
print(score)
>> 10
>> 35
>> 30
>> 60
Works with strings too — += joins strings:
message = 'Hello'
message += ', Zia!'
print(message)
>> Hello, Zia!
09 Type Conversion — Changing a Variable's Type
Sometimes you need to convert a variable from one type to another. Python has built-in functions for this. This is called type casting or type
conversion.
Function Converts To Example Result
int(x) Integer int('42') 42
float(x) Float float('3.14') 3.14
str(x) String str(100) '100'
bool(x) Boolean bool(0) False
list(x) List list('abc') ['a','b','c']
tuple(x) Tuple tuple([1,2,3]) (1, 2, 3)
round(x) Rounded int round(3.7) 4
Converting between numbers:
x = 9.99
print(int(x)) # cuts off decimal — does NOT round
print(round(x)) # rounds to nearest whole
y = 5
print(float(y)) # adds decimal point
>> 9
>> 10
>> 5.0
Converting numbers to strings (for joining text):
age = 25
message = 'I am ' + str(age) + ' years old.'
print(message)
>> I am 25 years old.
Bool conversion rules — what is True and False:
print(bool(0)) # False — zero is False
print(bool(1)) # True — any non-zero is True
print(bool('')) # False — empty string is False
print(bool('Zia')) # True — non-empty string is True
print(bool([])) # False — empty list is False
print(bool([1,2])) # True — non-empty list is True
print(bool(None)) # False — None is always False
>> False
>> True
>> False
>> True
>> False
>> True
>> False
10 Constants — Variables That Should Not Change
A constant is a variable whose value is set once and should never be changed during the program. Python has no strict constant keyword — by
convention, constants are written in ALL_CAPS to signal to other programmers: do not change this value.
PI = 3.14159265
MAX_STUDENTS = 40
SCHOOL_NAME = 'Leeds School & College'
TAX_RATE = 0.15
PASSING_MARKS = 50
radius = float(input('Enter radius: '))
area = PI * radius ** 2
print(f'Area = {area:.2f}')
>> Enter radius: 7
>> Area = 153.94
■ Python will NOT stop you from changing a constant — it is purely a naming convention to communicate intent. The ALL_CAPS name is a
warning: this should not be changed.
11 Variable Scope — Local vs Global
Scope means: where in your program a variable can be seen and used. Python has two main scopes — local and global.
Global variable — created outside any function, accessible everywhere:
school = 'Leeds School' # global variable
def show_school():
print(school) # can read global variable
show_school()
print(school)
>> Leeds School
>> Leeds School
Local variable — created inside a function, only exists there:
def calculate():
result = 100 # local variable — only inside this function
print(result)
calculate()
print(result) # NameError: result is not defined here
>> 100
Using global keyword to modify a global inside a function:
count = 0 # global
def increment():
global count # tell Python: use the global one
count += 1
increment()
increment()
increment()
print(count)
>> 3
■ Avoid using global variables when possible. They make code harder to understand and debug. Prefer passing values as function arguments.
12 Deleting a Variable — del
The del keyword removes a variable completely from memory. After deletion, trying to use it gives a NameError.
name = 'Zia'
print(name)
del name
print(name) # NameError: name 'name' is not defined
>> Zia
Deleting multiple variables at once:
a = 1
b = 2
c = 3
del a, b, c
■ del is rarely needed in normal programs. Python manages memory automatically. Use it when you want to free up memory for very large data.
13 Checking if a Variable Exists — try/except and 'in'
Sometimes you need to check whether a variable has been defined before using it.
Using try/except:
try:
print(username)
except NameError:
print('Variable username does not exist yet.')
>> Variable username does not exist yet.
Checking in a dictionary (for named values):
data = {'name': 'Zia', 'age': 25}
if 'name' in data:
print(data['name'])
>> Zia
Check if variable is None:
result = None
if result is None:
print('No result yet.')
else:
print(f'Result: {result}')
>> No result yet.
14 Variable Identity and Equality — is vs ==
Python has two ways to compare variables. Understanding the difference is important.
== compares VALUES — are the contents equal?
is compares IDENTITY — are they the exact same object in memory?
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True — same values
print(a is b) # False — different objects in memory
print(a is c) # True — c points to the SAME object as a
>> True
>> False
>> True
Use 'is' for None checks — best practice:
result = None
if result is None: # correct way
print('Empty')
if result == None: # works but not recommended
print('Empty')
■ Always use 'is None' and 'is not None' when checking for None. Use == for comparing values like numbers and strings.
15 String Variables in Detail
Strings are the most commonly used variable type. Here are all the key ways to work with string variables.
Creating strings — four ways:
s1 = 'single quotes'
s2 = "double quotes"
s3 = '''triple single — can span
multiple lines'''
s4 = """triple double — also
multiple lines"""
String operations:
first = 'Zia'
last = 'Ahmed'
full = first + ' ' + last # concatenation
print(full)
print(len(full)) # length
print([Link]()) # ALL CAPS
print([Link]()) # all lowercase
print([Link]('Zia','Ali')) # replace
print(full[0]) # first character
print(full[-1]) # last character
print(full[0:3]) # slice: first 3 chars
>> Zia Ahmed
>> 9
>> ZIA AHMED
>> zia ahmed
>> Ali Ahmed
>> Z
>> d
>> Zia
Checking string content:
print('Zia' in full) # True — is 'Zia' inside?
print([Link]('Zia')) # True
print([Link]('Ahmed')) # True
print([Link]('a')) # how many 'a' ?
>> True
>> True
>> True
>> 2
16 Numeric Variables in Detail
Integers and floats are the two main numeric types. Python also supports complex numbers (advanced).
Integer operations:
a = 17
b = 5
print(a + b) # 22 — addition
print(a - b) # 12 — subtraction
print(a * b) # 85 — multiplication
print(a / b) # 3.4 — division (always float)
print(a // b) # 3 — floor division (integer result)
print(a % b) # 2 — modulus (remainder)
print(a ** b) # 1419857 — power
>> 22
>> 12
>> 85
>> 3.4
>> 3
>> 2
>> 1419857
Useful number functions:
print(abs(-45)) # 45 — absolute value
print(max(3, 7, 1)) # 7 — largest
print(min(3, 7, 1)) # 1 — smallest
print(sum([5,10,15])) # 30 — sum of list
print(round(3.567, 2)) # 3.57 — round to 2 decimals
print(pow(2, 10)) # 1024 — 2 to the power 10
>> 45
>> 7
>> 1
>> 30
>> 3.57
>> 1024
Float formatting in output:
pi = 3.14159265358979
print(f'{pi:.2f}') # 2 decimal places
print(f'{pi:.5f}') # 5 decimal places
print(f'{pi:10.3f}') # width 10, 3 decimals
>> 3.14
>> 3.14159
>> 3.142
17 List Variables — Storing Multiple Values
A list variable stores multiple values in one place, in order. Each value has an index starting from 0.
fruits = ['Apple', 'Mango', 'Banana', 'Orange']
marks = [85, 90, 78, 92, 88]
print(fruits[0]) # Apple — first item
print(fruits[-1]) # Orange — last item
print(marks[2]) # 78 — third item
print(len(marks)) # 5 — number of items
>> Apple
>> Orange
>> 78
>> 5
Modifying a list:
[Link]('Grapes') # add to end
[Link](1, 'Peach') # insert at position 1
[Link]('Mango') # remove by value
[Link]() # remove last item
fruits[0] = 'Strawberry' # change item at index 0
print(fruits)
>> ['Strawberry', 'Peach', 'Banana', 'Orange']
List operations:
nums = [3, 1, 4, 1, 5, 9, 2]
print(sum(nums)) # total
print(max(nums)) # largest
print(min(nums)) # smallest
print(sorted(nums)) # sorted copy
>> 25
>> 9
>> 1
>> [1, 1, 2, 3, 4, 5, 9]
18 Dictionary Variables — Storing Key-Value Pairs
A dictionary stores data as key: value pairs. Use the key to look up its value, like a real dictionary where you look up a word to find its meaning.
student = {
'name' : 'Zia Ahmed',
'age' : 25,
'city' : 'DI Khan',
'marks' : 92
}
print(student['name'])
print(student['marks'])
>> Zia Ahmed
>> 92
Adding, changing, deleting:
student['email'] = 'zia@[Link]' # add new key
student['marks'] = 95 # update value
del student['city'] # delete key
print(student)
>> {'name': 'Zia Ahmed', 'age': 25, 'marks': 95, 'email': 'zia@[Link]'}
Useful dictionary methods:
print([Link]()) # all keys
print([Link]()) # all values
print('name' in student) # check if key exists
print([Link]('phone', 'N/A')) # safe get with default
>> dict_keys(['name', 'age', 'marks', 'email'])
>> dict_values(['Zia Ahmed', 25, 95, 'zia@[Link]'])
>> True
>> N/A
19 Common Variable Errors and How to Fix Them
These are the most frequent mistakes beginners make with variables.
Error 1 — NameError: using a variable before defining it:
print(score) # NameError: name 'score' is not defined
score = 100 # CORRECT: define first, then use
print(score)
Error 2 — TypeError: wrong type operation:
age = '25'
print(age + 1) # TypeError: can only concatenate str to str
age = int('25') # CORRECT: convert first
print(age + 1)
Error 3 — Typo in variable name:
student_name = 'Zia'
print(studentname) # NameError: typo!
print(student_name) # CORRECT
Error 4 — Confusion between = and ==:
if score = 100: # SyntaxError: = is assignment, not comparison
if score == 100: # CORRECT: == for comparison
print('Perfect!')
Error 5 — Using a Python keyword as variable name:
list = [1, 2, 3] # Overwrites built-in 'list' — bad practice!
for = 10 # SyntaxError
my_list = [1, 2, 3] # CORRECT: use a different name
■ Never name your variables list, dict, str, int, float, input, print — these are Python built-in names and overwriting them causes confusing bugs.
20 Complete Real-World Example — Student Record System
This program puts everything together: multiple variable types, assignment, input, conditions, and output.
# ■■ Student Result Calculator ■■■■■■■■■■■■■■■■■■■■■■■■■
PASSING_MARKS = 50 # constant
print('=== Student Result System ===')
name = input('Student Name: ').strip()
roll_no = input('Roll Number: ').strip()
english = int(input('English Marks (100): '))
maths = int(input('Maths Marks (100): '))
science = int(input('Science Marks (100): '))
total = english + maths + science
average = total / 3
percentage = (total / 300) * 100
if average >= 80: grade = 'A'
elif average >= 70: grade = 'B'
elif average >= 60: grade = 'C'
elif average >= 50: grade = 'D'
else: grade = 'F'
has_passed = average >= PASSING_MARKS
status = 'PASS' if has_passed else 'FAIL'
print(f'\n--- Result Card ---')
print(f'Name : {name}')
print(f'Roll No : {roll_no}')
print(f'English : {english}')
print(f'Maths : {maths}')
print(f'Science : {science}')
print(f'Total : {total}/300')
print(f'Average : {average:.1f}')
print(f'Percentage: {percentage:.2f}%')
print(f'Grade : {grade}')
print(f'Result : {status}')
>> === Student Result System ===
>> Student Name: Zia Ahmed
>> Roll Number: 101
>> English Marks (100): 85
>> Maths Marks (100): 90
>> Science Marks (100): 78
>> --- Result Card ---
>> Name : Zia Ahmed
>> Roll No : 101
>> English : 85
>> Maths : 90
>> Science : 78
>> Total : 253/300
>> Average : 84.3
>> Percentage: 84.33%
>> Grade : A
>> Result : PASS
■ Quick Reference — Python Variables at a Glance
Topic Code Example Notes
Create variable name = 'Zia' Use = to assign
Integer age = 25 Whole number
Float height = 5.9 Decimal number
String city = 'DI Khan' Text in quotes
Boolean flag = True True or False only
None result = None No value yet
Check type type(age) Returns class name
Reassign age = 30 Old value replaced
Multi-assign a, b = 10, 20 Two at once
Same value a = b = c = 0 All get same value
Swap a, b = b, a No temp variable
Add to variable score += 10 Short for score=score+10
Convert to int int('42') String to integer
Convert to float float('3.14') String to float
Convert to string str(100) Number to string
Delete variable del name Removes from memory
Global in function global x Access global x inside fn
Constant convention MAX = 100 ALL_CAPS = do not change
None check if x is None: Use 'is', not ==
✓ Golden Rule: Give variables clear, descriptive names. A name like 'student_total_marks' is always better than 'x' or 'val'.
End of Guide — Happy Coding! ■