What are Variables?
A variable is a container for storing data values. In Python:
✔ Variables do not need explicit declaration.
✔ The type of the variable is automatically determined.
✔ Variable names are case-sensitive.
Example:
name = "Alice" # String age = 25 # Integer height = 5.6 # Float is_student = True # Boolean print(name, age, height, is_student)
1. Variable Naming Rules
✅ Valid variable names:
✔ Must start with a letter (a-z, A-Z) or an underscore (_).
✔ Can contain letters, numbers, and underscores.
✔ Cannot use Python keywords (like if, while, class).
❌ Invalid variable names:
2name = "John" # ❌ Cannot start with a number my-name = "Doe" # ❌ Hyphens are not allowed class = "Python" # ❌ "class" is a reserved keyword
✅ Correct Examples:
_name = "Alice" myVar = 10 age_25 = 25
2. Assigning Values to Variables
Python allows dynamic typing, meaning you don’t need to declare the type explicitly.
x = 10 # Integer y = "Hello" # String z = 3.14 # Float print(x, y, z)
3. Multiple Variable Assignments
✔ Assigning the same value to multiple variables:
a = b = c = 100 print(a, b, c) # Output: 100 100 100
✔ Assigning different values in one line:
x, y, z = 5, "Python", 3.14 print(x, y, z) # Output: 5 Python 3.14
4. Type Checking & Conversion
✔ Check Data Type:
x = 10 print(type(x)) # Output: <class 'int'>
✔ Convert Data Types:
x = str(10) # Convert integer to string
y = int("20") # Convert string to integer
z = float(5) # Convert integer to float
print(x, y, z)
5. Variable Scope
✔ Local Variable (Defined inside a function):
def my_function():
local_var = "I am local"
print(local_var)
my_function()
# print(local_var) # ❌ This will cause an error (not accessible outside the function)
✔ Global Variable (Accessible throughout the program):
global_var = "I am global"
def my_function():
print(global_var) # Accessible inside function
my_function()
print(global_var) # Accessible outside function too
✔ Modifying a Global Variable Inside a Function:
count = 0
def update_count():
global count # Use global keyword
count += 1
update_count()
print(count) # Output: 1
6. Deleting a Variable
✔ Use del keyword to remove a variable:
x = 100 del x # Deletes x # print(x) # ❌ This will cause an error (x is deleted)
7. Constants in Python
Python does not have built-in constants, but you can use uppercase variable names to indicate they should not be changed.
PI = 3.14159 # Constant (By convention) GRAVITY = 9.8
8. Best Practices for Variables
✅ Use descriptive variable names (avoid x, y, z).
✅ Follow snake_case for variable names (user_name, total_price).
✅ Avoid using reserved keywords.
✅ Use global variables sparingly.