Python Notes
Python variables ko samjhein — declaration, assignment, naming rules, scope, multiple assignment, aur memory model ke saath complete guide.
Hindi: Variable matlab ek naam-wala container — jaise ek dabbe par label lagana. Jaise aap keh sakte hain "is dabbe mein atta hai" — Python mein flour = 5 matlab "flour naam ke container mein 5 rakhna."2. Creating Variables
In Python, you don't need to declare a variable before using it. Just assign a value!
Hindi: Python mein variable banane ke liye sirfnaam = valuelikhna hota hai. Koiint,stringyavartype declare nahi karna padta — Python khud samajh jaata hai!
# Creating variables with assignment operator (=)
name = "Rahul Kumar" # string
age = 25 # integer
height = 5.9 # float
is_student = True # boolean
# Print all
print(name)
print(age)
print(height)
print(is_student)Rahul Kumar 25 5.9 True
3. Python is Dynamically Typed
Python figures out the type automatically based on the value you assign.
Hindi: Python "dynamically typed" hai — matlab aapko type batane ki zaroorat nahi. x = 10 likhne par Python samjh jaata hai ki yeh integer hai. Ek hi variable ko alag types dene bhi kar sakte hain!<class 'int'> <class 'str'> <class 'float'> <class 'bool'> <class 'list'>
Dynamic vs Static Typing Comparison
| Feature | Python (Dynamic) | Java/C++ (Static) |
|---|---|---|
| Type declaration | Not needed | Required |
| Example | x = 10 | int x = 10; |
| Change type | Allowed | Not allowed |
| Speed | Slower | Faster |
| Flexibility | High | Low |
| Type checking | Runtime | Compile-time |
4. Variable Assignment
Simple Assignment
# Single assignment
city = "Mumbai"
population = 20_667_656 # underscore for readability (1000s separator)
area = 603.4
print(f"{city}: Population = {population:,}, Area = {area} km²")Mumbai: Population = 20,667,656, Area = 603.4 km²
Multiple Assignment (Same Value)
# Assign same value to multiple variables
a = b = c = 0
print(a, b, c) # 0 0 0
# Useful for initialization
x = y = z = None
print(x, y, z) # None None None0 0 0 None None None
Multiple Assignment (Different Values)
Priya 22 Delhi Delhi: 28.6139°N, 77.209°E
Swap Variables
# Traditional swap (other languages use temp variable)
# temp = a; a = b; b = temp
# Python's elegant swap — NO temp variable needed!
a = 10
b = 20
print(f"Before: a={a}, b={b}")
a, b = b, a # ← Python magic!
print(f"After: a={a}, b={b}")Before: a=10, b=20 After: a=20, b=10
Hindi: Python mein do variables swap karna bahut aasaan hai — a, b = b, a bas itna! Doosri languages mein 3 lines lagti hain.5. Augmented Assignment Operators
score = 100
score += 50 # score = score + 50
print(f"After += 50: {score}")
score -= 30 # score = score - 30
print(f"After -= 30: {score}")
score *= 2 # score = score * 2
print(f"After *= 2: {score}")
score //= 3 # score = score // 3 (integer division)
print(f"After //= 3: {score}")
score **= 2 # score = score ** 2 (power)
print(f"After **= 2: {score}")
score %= 1000 # score = score % 1000 (remainder)
print(f"After %= 1000: {score}")After += 50: 150 After -= 30: 120 After *= 2: 240 After //= 3: 80 After **= 2: 6400 After %= 1000: 400
6. Variable Naming Rules
Rules (Mandatory)
# Valid examples
student_name = "Amit"
_private = "secret"
__very_private = "more secret"
count99 = 100
MAX_SIZE = 1000
myVariable = "camelCase also valid"
print(student_name, count99, MAX_SIZE)Amit 100 1000
Naming Conventions (PEP 8 Best Practices)
# Variables and functions — snake_case
student_name = "Rahul"
total_marks = 450
is_passed = True
def calculate_percentage(marks, total):
return (marks / total) * 100
# Constants — UPPER_SNAKE_CASE
PI = 3.14159
GRAVITY = 9.81
MAX_STUDENTS = 60
DATABASE_URL = "localhost:5432"
# Classes — PascalCase (CamelCase)
class StudentRecord:
pass
class BankAccount:
pass
# Private — single underscore prefix
_internal_counter = 0
# "Very private" — double underscore prefix
__secret_key = "abc123"
result = calculate_percentage(total_marks, 500)
print(f"{student_name}: {result}%")Rahul: 90.0%
7. Python Memory Model
Hindi: Python mein variables sirf "labels" hain — woh directly data store nahi karte, balki memory mein rakhe object ki taraf point karte hain. Yeh samajhna bahut important hai!
a = [1, 2, 3] b = [1, 2, 3] id(a) = 140234567890 (some memory address) id(b) = 140234567890 (SAME address) a is b: True After b.append(4): a = [1, 2, 3, 4] b = [1, 2, 3, 4]
ASCII Diagram — Variable References
# For integers (immutable), this behavior is safe:
x = 10
y = x
y = 20 # y now points to new object 20, x unchanged
print(f"x = {x}") # 10 — unchanged
print(f"y = {y}") # 20
print(f"id(x) = {id(x)}")
print(f"id(y) = {id(y)}") # different!x = 10 y = 20 id(x) = 9788896 (some address) id(y) = 9789216 (different address)
8. Variable Scope
# Global variable — accessible everywhere
global_var = "I am global"
def demo_scope():
# Local variable — only inside function
local_var = "I am local"
print(global_var) # can access global
print(local_var)
demo_scope()
print(global_var) # accessible outside
# print(local_var) # ❌ NameError — not accessible!I am global I am local I am global
The global Keyword
counter = 0 # global variable
def increment():
global counter # tell Python: use the global counter
counter += 1
print(f"Inside function: counter = {counter}")
increment()
increment()
increment()
print(f"Outside function: counter = {counter}")Inside function: counter = 1 Inside function: counter = 2 Inside function: counter = 3 Outside function: counter = 3
LEGB Rule — Variable Lookup Order
x = "global" # G — Global
def outer():
x = "enclosing" # E — Enclosing
def inner():
x = "local" # L — Local
print(x) # prints "local"
inner()
print(x) # prints "enclosing"
outer()
print(x) # prints "global"local enclosing global
9. Constants in Python
Python doesn't have true constants, but by convention we use UPPER_CASE:
# Constants — uppercase with underscores
PI = 3.14159265358979
SPEED_OF_LIGHT = 299_792_458 # m/s
GRAVITY = 9.81 # m/s²
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30 # seconds
BASE_URL = "https://api.wohotech.com"
def calculate_circle_area(radius):
return PI * radius ** 2
def calculate_circle_circumference(radius):
return 2 * PI * radius
r = 7
print(f"Area: {calculate_circle_area(r):.4f}")
print(f"Circumference: {calculate_circle_circumference(r):.4f}")Area: 153.9380 Circumference: 43.9823
10. Type Annotations (Python 3.5+)
# Optional type hints — doesn't enforce types but improves readability
name: str = "Rahul"
age: int = 25
gpa: float = 3.8
is_enrolled: bool = True
# Function with type annotations
def calculate_bmi(weight: float, height: float) -> float:
"""Calculate BMI given weight (kg) and height (m)."""
return round(weight / (height ** 2), 2)
bmi = calculate_bmi(70.5, 1.75)
print(f"Name: {name}, Age: {age}")
print(f"BMI: {bmi}")Name: Rahul, Age: 25 BMI: 23.02
11. The Walrus Operator := (Python 3.8+)
High score found: 95 (random, may vary)
12. Deleting Variables
x = 100
y = 200
z = 300
print(x, y, z)
del x # delete single variable
print(y, z)
del y, z # delete multiple variables
# print(x) # ❌ NameError: name 'x' is not defined
print("Variables deleted successfully")100 200 300 200 300 Variables deleted successfully
Real-World Example: Student Grade System
# Student information variables
student_name = "Anjali Verma"
roll_number = 2301
subject_1_marks = 87
subject_2_marks = 92
subject_3_marks = 78
subject_4_marks = 95
subject_5_marks = 83
# Constants
TOTAL_SUBJECTS = 5
MAX_MARKS_PER_SUBJECT = 100
PASSING_PERCENTAGE = 33
# Calculations
total_marks = (subject_1_marks + subject_2_marks + subject_3_marks +
subject_4_marks + subject_5_marks)
max_possible = MAX_MARKS_PER_SUBJECT * TOTAL_SUBJECTS
percentage = (total_marks / max_possible) * 100
is_passed = percentage >= PASSING_PERCENTAGE
# Grade calculation
if percentage >= 90:
grade = "A+"
elif percentage >= 80:
grade = "A"
elif percentage >= 70:
grade = "B"
elif percentage >= 60:
grade = "C"
elif percentage >= 33:
grade = "D"
else:
grade = "F"
# Output
print("=" * 40)
print(f"STUDENT REPORT CARD")
print("=" * 40)
print(f"Name: {student_name}")
print(f"Roll No: {roll_number}")
print(f"Total: {total_marks}/{max_possible}")
print(f"Percentage: {percentage:.1f}%")
print(f"Grade: {grade}")
print(f"Result: {'PASS ✅' if is_passed else 'FAIL ❌'}")
print("=" * 40)======================================== STUDENT REPORT CARD ======================================== Name: Anjali Verma Roll No: 2301 Total: 435/500 Percentage: 87.0% Grade: A Result: PASS ✅ ========================================
Practice Exercises
Exercise 1 — Variable Basics
Create variables for:
- Your name, age, city, height (float), is_employed (bool)
- Print them all in a formatted sentence
Exercise 2 — Swap Without Temp
Given x = "Hello" and y = "World", swap their values and print both.
Exercise 3 — Multiple Assignment
Unpack this list into variables: data = ["Rahul", 22, "Delhi", 9.2] (name, age, city, gpa)
Exercise 4 — Augmented Assignment
Start with balance = 10000. Apply these operations:
- Add 5000 (salary)
- Subtract 1200 (rent)
- Subtract 800 (groceries)
- Multiply remaining by 1.04 (4% interest)
- Print final balance
Exercise 5 — Scope
Write a function that modifies a global user_count variable using the global keyword.
Interview Questions
Q1. Is Python statically typed or dynamically typed? What's the difference? > Python is dynamically typed — variable types are determined at runtime based on assigned values. You don't declare types. In contrast, statically typed languages (Java, C++) require explicit type declarations and check types at compile time.
Q2. What is the difference between =, ==, and is in Python? > = is assignment (stores value), == checks value equality, is checks identity (same memory address/object). Example: a = [1,2]; b = [1,2]; a == b is True (same values), but a is b is False (different objects).
Q3. Explain variable scope and the LEGB rule. > Scope determines where a variable is accessible. Python uses LEGB: Local (inside function) → Enclosing (outer function) → Global (module level) → Built-in (Python's built-ins). Python searches in this order.
Q4. What happens when you do b = a with a list? > Both a and b reference the same list object. Modifying through b affects a too. To create an independent copy, use b = a.copy() or b = a[:].
Q5. How do Python constants differ from true constants? > Python has no built-in constant mechanism. By convention, variables in UPPER_CASE are treated as constants, but they can technically be changed. For true immutability, you can use typing.Final (Python 3.8+) or put constants in a frozen dataclass.
⚠️ Common Mistakes
1. Variable naam digit se shuru karna ❌
# Wrong ❌
1st_name = "Rahul" # SyntaxError!
# Correct ✅
first_name = "Rahul"Hindi: Variable ka naam kabhi bhi number se shuru nahi ho sakta — hamesha letter ya underscore _ se shuru karein.2. Assignment = aur Comparison == confuse karna ❌
# Wrong ❌ — yeh assign karega, compare nahi
if x = 10: # SyntaxError!
print("yes")
# Correct ✅
if x == 10:
print("yes")Hindi:=matlab value assign karna,==matlab compare karna. Bahut common mistake hai beginners mein!
3. Undefined variable use karna ❌
# Wrong ❌
print(salary) # NameError: name 'salary' is not defined
# Correct ✅
salary = 50000
print(salary)Hindi: Variable ko use karne se pehle usse value assign karna zaroori hai. Python mein sirf declare karna possible nahi — assign karna padta hai.
4. Mutable objects ko copy samajhna ❌
Hindi: Lists, dictionaries jaise mutable objects meinb = alikhne se dono SAME object ko point karte hain. Independent copy chahiye toh.copy()ya slicing[:]use karein.
5. global keyword bhoolna ❌
count = 0
# Wrong ❌
def increment():
count += 1 # UnboundLocalError!
# Correct ✅
def increment():
global count
count += 1Hindi: Function ke andar global variable ko modify karne ke liye global keyword zaroori hai, warna Python use local maanegi aur error degi.6. Case sensitivity ignore karna ❌
# Wrong ❌ — yeh ALAG variables hain!
Name = "Rahul"
name = "Priya"
NAME = "Amit"
print(Name, name, NAME) # Rahul Priya Amit — teeno different!Hindi: Python case-sensitive hai —Name,name, aurNAMEteeno alag variables hain. Consistent naming follow karein (prefersnake_case).
7. Python keywords ko variable naam rakhna ❌
# Wrong ❌
class = "10th" # SyntaxError!
for = "loop" # SyntaxError!
import = "module" # SyntaxError!
# Correct ✅
class_name = "10th"
loop_type = "for"
module_name = "os"Hindi: Python ke reserved words (if,else,class,for,while,import, etc.) ko variable naam ke roop mein use nahi kar sakte.
✅ Key Takeaways
- 📦 Variable ek label hai — yeh memory mein kisi object ko point karta hai, directly data store nahi karta.
- 🔄 Python dynamically typed hai — aapko type declare nahi karna padta, Python khud value dekh kar type decide karta hai.
- 📝 Assignment operator
=se variable banate hain —naam = valuebas itna hi kaafi hai. - 🐍 Naming rules yaad rakhein — letter/underscore se shuru, digits allowed baad mein, no spaces/special chars, no keywords.
- 🎯 PEP 8 conventions follow karein — variables ke liye
snake_case, constants ke liyeUPPER_CASE, classes ke liyePascalCase. - 🔗
b = a(mutable objects) se dono same object point karte hain — independent copy ke liye.copy()use karein. - 🌍 Scope matters — LEGB rule (Local → Enclosing → Global → Built-in) samjhein. Function mein global modify karne ke liye
globalkeyword use karein. - 🔀 Swap karna easy hai —
a, b = b, aPython ka elegant approach hai, temp variable ki zaroorat nahi. - 🏷️ Type annotations optional hain — code readability badhate hain lekin Python enforce nahi karta.
- 🗑️
delstatement se variables delete kar sakte hain — memory management mein helpful hai.
❓ FAQ
Q1. Kya Python mein variable declare karna zaroori hai? > Nahi! Python mein alag se declaration ki zaroorat nahi hoti. Aap directly x = 10 likh sakte hain — Python automatically type infer kar leta hai. Yeh Java/C++ se alag hai jahan int x = 10; likhna padta hai.
Q2. Ek variable ki type runtime pe change kar sakte hain kya? > Haan! Python dynamically typed hai, toh x = 10 ke baad x = "Hello" likh sakte hain — koi error nahi aayega. Lekin yeh best practice nahi hai kyunki code confusing ho sakta hai.
Q3. is aur == mein kya difference hai? > == value compare karta hai (dono ki value same hai ya nahi), jabki is identity check karta hai (dono same memory object hain ya nahi). Example: [1,2] == [1,2] → True, lekin [1,2] is [1,2] → False (different objects).
Q4. Global variable ko function ke andar kaise modify karein? > Function ke andar global variable_name likhein, phir modify karein. Bina global keyword ke, Python function ke andar ek naya local variable bana dega ya UnboundLocalError dega.
Q5. Python mein constants kaise banate hain? > Python mein true constants nahi hote. Convention hai ki UPPER_CASE mein likhe variables ko constant maana jaata hai (e.g., MAX_SIZE = 100). Python 3.8+ mein typing.Final use kar sakte hain type checker ke liye, lekin runtime pe phir bhi change ho sakta hai.
Q6. Variable naming mein _ (single underscore) aur __ (double underscore) ka kya matlab hai? > Single underscore _var ka matlab hai "private/internal use" (convention). Double underscore __var Python mein name mangling trigger karta hai — class ke andar variable ka naam change ho jaata hai taaki subclass accidentally override na kare.
Q7. Kya ek line mein multiple variables assign kar sakte hain? > Haan! Do tarike hain: (1) Same value — a = b = c = 0, (2) Different values — x, y, z = 1, 2, 3. Yeh tuple unpacking ke concept par based hai.
Q8. del statement kab use karna chahiye? > del tab use karein jab aapko explicitly kisi variable ko memory se hatana ho — jaise large data structures jinka kaam ho gaya. Normally Python ka garbage collector khud handle karta hai, lekin memory-intensive programs mein del helpful hai.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Variables.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, basics, variables, python variables
Related Python Master Course Topics