A variable is a name used to store or refer to a value in a Python program.
Variables allow us to store information such as:
- Names
- Age
- Prices
- Email addresses
- Numbers
- Lists
- Dictionaries
- Objects
- Results of calculations
Instead of repeatedly writing the same value, we can store it in a variable and use the variable whenever we need that value.
Simple Example
name = "Raj"
age = 25
print(name)
print(age)
Output:
Raj
25
Here:
name → variable
"Raj" → value
age → variable
25 → value
1. Creating a Variable
Python does not require a special keyword to create a variable.
Simply assign a value using =.
name = "John"
age = 20
city = "Kathmandu"
print(name)
print(age)
print(city)
The = operator assigns a value to a variable.
2. Understanding Variable Assignment
Consider:
x = 10
This means:
Store the value
10and associate it with the namex.
We can then use x in our program:
x = 10
print(x)
print(x + 5)
print(x * 2)
Output:
10
15
20
The variable can therefore be used wherever we need the stored value.
3. Variables Can Store Different Types of Values
Python variables can refer to different types of data.
name = "Raj"
age = 25
height = 5.8
is_student = True
print(name)
print(age)
print(height)
print(is_student)
Here:
name → string
age → integer
height → float
is_student → boolean
Python automatically determines the type based on the assigned value.
4. No Need to Declare the Variable Type
In some programming languages, you may need to specify the type of a variable.
For example, another language might require something like:
int age = 25
Python does not require this.
You simply write:
age = 25
Python understands that age currently refers to an integer.
This is one reason Python is called a dynamically typed language.
5. Checking the Type of a Variable
Use the type() function to find the type of the value.
name = "Raj"
age = 25
height = 5.8
active = True
print(type(name))
print(type(age))
print(type(height))
print(type(active))
Output:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
6. Variable Names
A variable name should clearly describe the value it represents.
Good examples:
student_name = "Raj"
student_age = 22
course_name = "Python"
course_duration = 8
Poor examples:
x = "Raj"
a = 22
z = "Python"
The second approach may work, but meaningful names make programs much easier to understand.
7. Python Variable Naming Rules
Python has rules that variable names must follow.
Rule 1: Start with a letter or underscore
Valid:
name = "Raj"
_age = 25
Invalid:
1name = "Raj"
A variable name cannot start with a number.
Rule 2: Numbers can appear after the first character
Valid:
student1 = "Raj"
student2 = "John"
course2026 = "Python"
Invalid:
1student = "Raj"
Rule 3: Spaces are not allowed
Invalid:
student name = "Raj"
Use an underscore instead:
student_name = "Raj"
Rule 4: Special characters are generally not allowed
Avoid:
student-name = "Raj"
student@name = "Raj"
Use:
student_name = "Raj"
Rule 5: Python is case-sensitive
These are different variables:
name = "Raj"
Name = "John"
NAME = "Sita"
print(name)
print(Name)
print(NAME)
Output:
Raj
John
Sita
Python treats uppercase and lowercase letters as different.
8. Naming Convention - snake_case
Python commonly uses snake_case for variable names.
Example:
first_name = "Raj"
last_name = "Kandel"
student_age = 25
course_name = "Python Bootcamp"
total_price = 5000
Words are separated using _.
Instead of:
studentname = "Raj"
prefer:
student_name = "Raj"
9. Avoid Python Keywords
Python has reserved keywords that already have special meanings.
For example:
if
else
for
while
class
def
return
import
True
False
None
You should not use these as variable names.
Invalid:
class = "Python"
Invalid:
if = 10
Python will produce a syntax error.
10. Checking Python Keywords
Python provides a module that can show Python's keywords.
import keyword
print(keyword.kwlist)
This displays the keywords supported by your installed Python version.
You can also check whether a word is a keyword:
import keyword
print(keyword.iskeyword("class"))
print(keyword.iskeyword("student"))
Output:
True
False
11. Assigning Multiple Variables
Python allows multiple variables to be assigned in one statement.
name, age, city = "Raj", 25, "Kathmandu"
print(name)
print(age)
print(city)
Output:
Raj
25
Kathmandu
This is called multiple assignment.
12. Assigning the Same Value to Multiple Variables
You can assign one value to several variables.
x = y = z = 100
print(x)
print(y)
print(z)
Output:
100
100
100
This can be useful when several variables need the same initial value.
13. Swapping Variables
Python makes it easy to swap two variables.
a = 10
b = 20
a, b = b, a
print(a)
print(b)
Output:
20
10
No temporary variable is required.
This is a useful Python feature.
14. Changing a Variable's Value
A variable can be assigned a new value.
age = 20
print(age)
age = 21
print(age)
Output:
20
21
The variable now refers to the new value.
15. A Variable Can Refer to Different Types
Python allows a variable to refer to different types of values at different times.
x = 100
print(x)
print(type(x))
x = "Hello"
print(x)
print(type(x))
Initially:
100
<class 'int'>
Later:
Hello
<class 'str'>
This behavior is related to Python's dynamic typing.
16. Variables and Objects
A useful way to understand Python variables is:
A variable is a name that refers to an object.
For example:
x = 100
Conceptually:
x ───────→ 100
If we do:
y = x
then:
x ───────→ 100
y ───────→ 100
Both names refer to the same integer object.
This concept becomes especially important when working with lists, dictionaries, and other mutable objects.
17. Assigning One Variable to Another
x = 100
y = x
print(x)
print(y)
Output:
100
100
Changing y later:
x = 100
y = x
y = 200
print(x)
print(y)
Output:
100
200
The assignment y = 200 makes y refer to another value.
18. Variables with Calculations
Variables can store calculation results.
price = 500
quantity = 3
total = price * quantity
print(total)
Output:
1500
This is one of the main reasons variables are useful in programming.
19. Updating a Variable
Suppose:
score = 50
We can update it:
score = score + 10
print(score)
Output:
60
Python also provides a shorter form:
score += 10
print(score)
20. Assignment Operators
Common assignment operators include:
| Operator | Example | Equivalent |
|---|---|---|
= | x = 10 | Assign |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
//= | x //= 5 | x = x // 5 |
%= | x %= 5 | x = x % 5 |
**= | x **= 5 | x = x ** 5 |
Example:
x = 10
x += 5
print(x)
x *= 2
print(x)
x -= 5
print(x)
21. Variables with Strings
Variables are commonly used to store text.
first_name = "Raj"
last_name = "Kandel"
full_name = first_name + " " + last_name
print(full_name)
Output:
Raj Kandel
22. Variables with Lists
A variable can store a list.
fruits = ["apple", "mango", "banana"]
print(fruits)
print(fruits[0])
Output:
['apple', 'mango', 'banana']
apple
23. Variables with Dictionaries
A variable can also refer to a dictionary.
student = {
"name": "Raj",
"age": 25,
"course": "Python"
}
print(student)
print(student["name"])
Output:
{'name': 'Raj', 'age': 25, 'course': 'Python'}
Raj
24. Variables with Tuples and Sets
Tuple:
coordinates = (27.7, 85.3)
print(coordinates)
Set:
skills = {"Python", "Django", "SQL"}
print(skills)
A variable can refer to almost any Python object.
25. Constants in Python
Python does not have a special constant keyword.
However, programmers commonly use UPPERCASE names to indicate that a value should be treated as a constant.
Example:
PI = 3.14159
MAX_LOGIN_ATTEMPTS = 5
COMPANY_NAME = "SkillMantra"
Python will not prevent you from changing these values:
PI = 4
But uppercase naming communicates:
This value is intended to remain unchanged.
26. Local and Global Variables - Introduction
Variable scope determines where a variable can be accessed.
For example:
name = "Raj"
def welcome():
print(name)
welcome()
Here name is defined outside the function, so it is a global variable.
We will study local and global scope in detail when we learn functions.
27. Checking Whether a Variable Exists
Python does not provide a simple exists() function for variables.
However, you can inspect the current namespace using:
x = 10
print("x" in globals())
Output:
True
This is more advanced and is generally not needed in beginner programs.
28. Deleting a Variable
The del statement can remove a variable.
x = 100
print(x)
del x
After deleting it:
print(x)
will produce a NameError because the variable name no longer exists.
29. None as a Variable Value
Python provides a special value called None.
None represents the absence of a value.
Example:
result = None
print(result)
print(type(result))
Output:
None
<class 'NoneType'>
This is useful when a value is not available yet.
For example:
student_email = None
Later:
student_email = "student@example.com"
30. User Input Stored in Variables
Variables become especially useful when combined with input().
name = input("Enter your name: ")
print("Welcome", name)
If the user enters:
Raj
the output becomes:
Welcome Raj
The value entered by the user is stored in the name variable.
31. Important: input() Returns a String
Consider:
age = input("Enter your age: ")
print(type(age))
Even if the user enters:
25
the type is:
<class 'str'>
If we need an integer, convert it:
age = int(input("Enter your age: "))
print(type(age))
Now the type is:
<class 'int'>
We will cover type conversion in more detail in the next lessons.
32. Variable Naming Best Practices
Good variable names make code easier to understand.
Good
student_name = "Raj"
student_age = 25
course_price = 15000
total_students = 50
Avoid vague names
x = "Raj"
a = 25
p = 15000
Unless the variable has a very small and obvious scope, descriptive names are better.
33. Avoid Overly Long Names
A variable name should be descriptive but not unnecessarily complicated.
Instead of:
the_total_number_of_students_registered_for_python_bootcamp = 50
use:
python_students = 50
The goal is:
Clear enough to understand, short enough to use comfortably.
34. Avoid Naming Variables After Built-in Functions
Python already has built-in functions such as:
print
len
list
str
int
sum
max
min
input
type
Avoid:
list = [1, 2, 3]
because now list no longer refers to the built-in list() constructor in that scope.
Similarly, avoid:
str = "Hello"
Prefer:
message = "Hello"
35. Practical Example : Student Information
student_name = "Raj"
student_age = 25
course_name = "Python Bootcamp"
course_duration = 8
course_price = 15000
print("Student:", student_name)
print("Age:", student_age)
print("Course:", course_name)
print("Duration:", course_duration, "weeks")
print("Price:", course_price)
This demonstrates how variables can represent real-world information.
36. Practical Example : Shopping Calculation
item_name = "Keyboard"
price = 1500
quantity = 2
total = price * quantity
print("Item:", item_name)
print("Price:", price)
print("Quantity:", quantity)
print("Total:", total)
Output:
Item: Keyboard
Price: 1500
Quantity: 2
Total: 3000
37. Practical Example : Student Result
student_name = "Raj"
python_marks = 85
database_marks = 78
web_marks = 90
total = python_marks + database_marks + web_marks
average = total / 3
print("Student:", student_name)
print("Total:", total)
print("Average:", average)
Here, variables make the calculation much easier to understand.
38. Copy Code
# ==========================================
# Python Variables
# ==========================================
# Creating variables
name = "Raj"
age = 25
height = 5.8
is_student = True
print(name)
print(age)
print(height)
print(is_student)
# Checking data types
print(type(name))
print(type(age))
print(type(height))
print(type(is_student))
# Changing a variable
age = 26
print("Updated age:", age)
# Multiple assignment
first_name, last_name, city = "Raj", "Kandel", "Kathmandu"
print(first_name)
print(last_name)
print(city)
# Same value assigned to multiple variables
x = y = z = 100
print(x)
print(y)
print(z)
# Swapping variables
a = 10
b = 20
a, b = b, a
print("a:", a)
print("b:", b)
# Calculation using variables
price = 500
quantity = 3
total = price * quantity
print("Total:", total)
# Updating a variable
score = 50
score += 10
print("Updated score:", score)
# String variables
first_name = "Raj"
last_name = "Kandel"
full_name = first_name + " " + last_name
print(full_name)
# List variable
fruits = ["apple", "mango", "banana"]
print(fruits)
# Dictionary variable
student = {
"name": "Raj",
"age": 25,
"course": "Python"
}
print(student)
# None
result = None
print(result)
print(type(result))
39. Practice Exercise 1 : Personal Information
Create variables for:
Name
Age
City
Country
Profession
Print all the information.
40. Practice Exercise 2 : Shopping Cart
Create:
product_name
price
quantity
Calculate:
total = price × quantity
Print the result.
41. Practice Exercise 3 : Student Marks
Create variables for three subjects:
python_marks
database_marks
web_marks
Calculate:
- Total
- Average
Print all results.
42. Practice Exercise 4 : Variable Swapping
Create:
a = 100
b = 200
Swap the values so that:
a = 200
b = 100
Do it without creating a third variable.
43. Practice Exercise 5 : User Input
Create a program that asks the user for:
- Name
- Age
- Course
Then print:
Welcome Raj!
You are 25 years old.
You are learning Python.
Hint:
name = input("Enter your name: ")
44. Challenge : Simple Invoice
Create a small invoice program.
Store:
customer_name
product_name
price
quantity
discount
Calculate:
subtotal = price × quantity
discount_amount = subtotal × discount / 100
final_amount = subtotal - discount_amount
Then display:
Customer: Raj
Product: Laptop
Price: 80000
Quantity: 1
Subtotal: 80000
Discount: 10%
Final Amount: 72000
Try solving it without copying the solution.