.
Local Variables
A local variable is declared inside a function and can only be used
within that function.
It exists only during the execution of the function.
Once the function finishes, the variable is destroyed.
Example:
python
CopyEdit
def greet(): message = "Hello, World!" # Local variable print(message) greet() #
print(message) # This would cause an error because 'message' is not accessible outside
the function.
2. Global Variables
A global variable is declared outside of a function and is
accessible throughout the program.
It can be used inside and outside functions.
However, if you need to modify a global variable inside a function, you
must use the global keyword.
Example:
python
CopyEdit
name = "Alice" # Global variable def change_name(): global name # Allows modification
of the global variable name = "Bob" print(name) # Output: Alice change_name()
print(name) # Output: Bob
How global Works
By default, variables inside a function are local. If a variable with the
same name as a global variable is assigned inside a function, it creates a
new local variable instead of modifying the global one.
Example (Without global)
python
CopyEdit
x = 10 # Global variable def change_x(): x = 20 # This creates a new local variable, does
NOT modify the global 'x' print("Inside function:", x) # Output: Inside function: 20
change_x() print("Outside function:", x) # Output: Outside function: 10 (unchanged)
Explanation:
Inside change_x(), x = 20 creates a local variable named x, which is
different from the global x.
Using global to Modify a Global Variable
To modify the global variable inside a function, use the global keyword.
Example (With global)
python
CopyEdit
x = 10 # Global variable def change_x(): global x # Refers to the global 'x' x = 20 #
Modifies the global variable print("Inside function:", x) # Output: Inside function: 20
change_x() print("Outside function:", x) # Output: Outside function: 20 (changed)
all by Value vs Call by
E
Reference in Python
🔹 What is Call by Value and Call by Reference?
These are two ways to pass arguments to functions:
1️⃣Call by Value → A copy of the value is passed, and changes inside the
function do not affect the original variable.
2️⃣Call by Reference → The reference (memory address) of the original object is
passed, so changes inside the function affect the original variable.
🔹 How Python Handles Function Arguments?
Python does not use traditional "Call by Value" or "Call by Reference".
Instead, it follows Call by Object Reference (or Call by Sharing).
🔹 Immutable objects (int, float, string, tuple) → Behave like Call by Value
🔹 Mutable objects (list, dictionary, set) → Behave like Call by Reference
🔹 Example of Call by Value (Immutable Objects)
When passing integers, floats, strings, or tuples, their values do not
change inside the function.
python
CopyEdit
def modify_value(x): x = 10 # Changing the value print("Inside function:", x) num = 5
modify_value(num) print("Outside function:", num) # Original value remains unchanged
Output:
bash
CopyEdit
Inside function: 10
Outside function: 5
✔ num = 5 remains unchanged because integers are immutable.
🔹 Example of Call by Reference (Mutable Objects)
When passing lists, dictionaries, or sets, changes inside the function affect
the original object.
python
CopyEdit
def modify_list(lst): lst.append(4) # Modifying the original list print("Inside function:", lst)
numbers = [1, 2, 3] modify_list(numbers) print("Outside function:", numbers) # Original
list is modified
xplanation:
The global x statement tells Python that x refers to the global
variable, not a local one.
Any modification to x inside change_x() affects the global variable.
he return Statement in Python
The return statement is used inside a function to send a value back to the
caller. It terminates the function and returns data that can be stored in a
variable or used directly.
1. Returning a Single Value
python
CopyEdit
def square(num): return num * num result = square(5) print(result) # Output: 25
Explanation:
The function square(5) returns 25, which is stored in result.
Types of Function Arguments in Python (Detailed Explanation)
In Python, functions can accept different types of arguments. These help in writing flexible
and efficient code. The main types of function arguments are:
1. Required Arguments
2. Keyword Arguments
3. Arbitrary Keyword Arguments (**kwargs)
4. Default Arguments
5. Variable-Length/Arbitrary Arguments (*args)
Let's break them down in detail with examples.
1. Required Arguments
These are mandatory arguments that must be provided when calling a function.
If a required argument is missing, Python will raise an error.
Example:
def add(a, b):
return a + b
# Calling the function with required arguments
print(add(5, 3)) # ✅ Output: 8
# Calling without required arguments
print(add(5)) # ❌ TypeError: missing 1 required positional argument
Key Points:
The function add(a, b) expects two required arguments.
If you pass both values, the function executes correctly.
If any required argument is missing, Python throws an error.
2. Keyword Arguments
These allow you to specify argument names while calling a function.
Order does not matter since the argument names are explicitly mentioned.
Example:
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
# Using keyword arguments
introduce(name="Alice", age=25) # ✅ Output: My name is Alice and I am 25
years old.
introduce(age=30, name="Bob") # ✅ Output: My name is Bob and I am 30
years old.
Key Points:
The order of arguments doesn’t matter because Python matches names explicitly.
Improves code readability and avoids confusion.
3. Arbitrary Keyword Arguments (**kwargs)
Used when you don’t know the number of keyword arguments beforehand.
The function receives arguments as a dictionary (dict).
Useful when dealing with dynamic data.
Example:
def person_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
# Calling function with varying keyword arguments
person_info(name="Alice", age=25, city="New York")
# ✅ Output:
# name: Alice
# age: 25
# city: New York
person_info(name="Bob", country="USA")
# ✅ Output:
# name: Bob
# country: USA
Key Points:
**kwargs collects multiple keyword arguments into a dictionary.
The function can handle any number of keyword arguments dynamically.
Useful for creating flexible functions.
4. Default Arguments
Assigns a default value to a parameter.
If the argument is not provided, the default value is used.
Helps make functions optional in some cases.
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet("Alice") # ✅ Output: Hello, Alice!
greet() # ✅ Output: Hello, Guest!
Key Points:
The function greet(name="Guest") has a default argument "Guest".
If an argument is passed, it overrides the default.
If no argument is given, the default value is used.
5. Variable-Length/Arbitrary Arguments (*args)
Used when you don’t know how many arguments will be passed.
The function receives multiple values as a tuple (tuple).
Useful for handling dynamic lists of values.
Example:
def sum_numbers(*nums):
return sum(nums)
# Calling function with different numbers of arguments
print(sum_numbers(1, 2, 3)) # ✅ Output: 6
print(sum_numbers(10, 20, 30, 40)) # ✅ Output: 100
print(sum_numbers()) # ✅ Output: 0
Key Points:
*args collects multiple positional arguments into a tuple.
The function can process any number of arguments dynamically.
Combining Different Argument Types
You can combine multiple argument types in a function. The order should be:
1. Required arguments
2. *args (Variable-length positional arguments)
3. Default arguments
4. **kwargs (Variable-length keyword arguments)
Example:
def complete_function(a, b, *args, c=100, **kwargs):
print(f"a: {a}, b: {b}, args: {args}, c: {c}, kwargs: {kwargs}")
# Calling the function
complete_function(1, 2, 3, 4, 5, c=50, name="Alice", age=25)
# ✅ Output:
# a: 1, b: 2, args: (3, 4, 5), c: 50, kwargs: {'name': 'Alice', 'age': 25}
Key Points:
a and b are required arguments.
*args captures extra positional arguments ((3, 4, 5)).
c=100 is a default argument, but it can be overridden.
**kwargs captures extra keyword arguments ({'name': 'Alice', 'age': 25'}).
Summary Table
Argument Type Symbol Description Example
Required Must be provided, or Python
None func(1, 2)
Arguments raises an error
Keyword Pass arguments using names, func(name="Alice",
None age=25)
Arguments order doesn’t matter
Argument Type Symbol Description Example
Arbitrary Accepts any number of named
func(name="Alice",
Keyword **kwargs arguments, stored in a age=25, city="NY")
Arguments dictionary
Default Uses default values if no
param=value func(name="Guest")
Arguments argument is given
Accepts any number of
Variable-Length
*args positional arguments, stored func(1, 2, 3, 4, 5)
Arguments
in a tuple
Best Practices for Function Arguments
✅ Use required arguments for necessary inputs.
✅ Use keyword arguments to improve readability.
✅ Use *args and **kwargs for flexibility.
✅ Avoid excessive use of global variables inside functions.
✅ Keep function arguments minimal and clear.
Would you like me to write a real-world example using these concepts? 😊
Iterator ko Hinglish mein Samjhana 😃
Iterator ek aisa object hota hai jo ek sequence ke elements ko ek-
ek karke access karta hai, bina poore data ko memory mein load kiye.
Matlab, jab bhi next element chahiye hota hai, tabhi generate hota
hai.
Iterator Ka Basic Concept
Python mein, koi bhi object iterator tab hota hai jab
usme __iter__() aur __next__() methods hote hain.
👉 Iterator se fayda kya hai?
✅ Memory efficient hota hai – Poora data ek sath store nahi hota, bas
ek element memory mein aata hai.
✅ Large data handle karne ke liye best hai – Poore 1 crore numbers
ko ek list mein store karna heavy ho sakta hai, lekin iterator ek-ek karke
deta hai.
Ek Simple Example
python
CopyEdit
numbers = [10, 20, 30, 40] # Ek normal list it = iter(numbers) # List ka iterator banaya
print(next(it)) # Output: 10 print(next(it)) # Output: 20 print(next(it)) # Output: 30
print(next(it)) # Output: 40 print(next(it)) # StopIteration error dega (kyunki aur
elements nahi hain)
🛑 Samajhne ki baat:
iter(numbers) ek iterator object banata hai.
next(it) har baar agli value fetch karta hai, bina poori list ko store
kiye.
Jab sari values khatam ho jati hain, to StopIteration error aa jata hai.
Generator ko Hinglish mein Samajhna 😃
Generator iterator jaisa hi hota hai, par aur bhi zyada powerful aur
easy hota hai.
Yeh yield keyword ka use karta hai jo execution ko pause karke state save
kar leta hai.
1. Generator Kya Hota Hai?
🔹 Generator ek aise function ko bolte hain jo yield keyword ka use karke
values ko ek-ek karke return karta hai, bina sari values ko memory me store
kiye.
🔹 Normal function return karta hai, lekin generator yield karta hai jo
execution ko pause karke wapas wahi se resume karta hai.
Decorator Kya Hota Hai? (Hinglish Mein Samajhna) 🚀
Decorator Python ka ek powerful feature hai jo kisi function ka behavior
badalne ya enhance karne ke liye use hota hai, bina uska code directly
modify kiye.
Matlab, function ke andar kuch naya add karna ho bina usko directly
chhed-chaad kiye, to decorator use karte hain. 😃
1. Simple Example (Decorator Samajhne Ke Liye)
python
CopyEdit
def my_decorator(func): def wrapper(): print("Function call hone se pehle kuch kar rahe
hain...") func() print("Function call hone ke baad kuch kar rahe hain...") return wrapper
@my_decorator def say_hello(): print("Hello, World!") say_hello()
✅ Output:
sql
CopyEdit
Function call hone se pehle kuch kar rahe hain...
Hello, World!
Function call hone ke baad kuch kar rahe hain...
📌 Samajhne ki Baat:
@my_decorator ek function ko modify kar raha hai bina uska asli code badle.
wrapper() ek extra kaam kar raha hai function ke pehle aur baad.
say_hello() seedha call nahi ho raha, balki wrapper() ke through ho raha
hai.
@ Symbol Ka Magic
Python me decorator use karne ka best tarika @decorator_name likhna hota hai.
python
CopyEdit
@decorator_function # Iska matlab hai ki yeh function decorate ho raha hai def display():
print("I am a simple function")
➡ Yeh likhne se hume decorated_display =
decorator_function(display) likhne ki zaroorat nahi hoti.
Decorator Kya Hota Hai? (Hinglish Mein Samajhna) 🚀
Decorator Python ka ek powerful feature hai jo kisi function ka behavior
badalne ya enhance karne ke liye use hota hai, bina uska code directly
modify kiye.
Matlab, function ke andar kuch naya add karna ho bina usko directly
chhed-chaad kiye, to decorator use karte hain. 😃
1. Simple Example (Decorator Samajhne Ke Liye)
python
CopyEdit
def my_decorator(func): def wrapper(): print("Function call hone se pehle kuch kar rahe
hain...") func() print("Function call hone ke baad kuch kar rahe hain...") return wrapper
@my_decorator def say_hello(): print("Hello, World!") say_hello()
✅ Output:
Difference Between List, Tuple, and Dictionary in
Python 🐍
Feature List (list) Tuple (tuple) Dictionary (dict)
Ordered collection of Ordered Unordered collection of key-
Definition elements but immutable collection value pairs
{"name": "Alice",
Syntax [1, 2, 3] (1, 2, 3) "age": 25}
✅ Yes, values can be
✅ Yes, elements can be ❌ No, elements cannot be modified, but keys must be
Mutable? (Changeable) modified modified immutable
✅ Yes for values, ❌ No for
Duplicates Allowed? ✅ Yes ✅ Yes keys
✅ Yes, supports indexing & ✅ Yes, supports indexing & ❌ No direct indexing, uses
Indexing & Slicing slicing slicing keys
Faster than lists (due to Faster lookups (due to
Performance Slower than tuples immutability) hashing)
When you need a dynamic When you need a fixed collection When you need key-value
Use Case collection that can change that should not change pairs for fast lookups
Uses more memory than Uses more memory due to
Memory Usage tuples Uses less memory than lists key-value storage
Fast (Optimized for key
Looping Speed Slower than tuple Faster than list lookups)
dict[key] =
Adding Elements append(), insert() ❌ Not possible (Immutable) value, update()
Removing Elements remove(), pop() ❌ Not possible pop(key), del dict[key]
When data needs frequent When data should remain When data needs quick
Best Use Case modifications unchanged lookups
Example Code for Each
1️⃣List Example (Mutable)
python
CopyEdit
my_list = [1, 2, 3] my_list.append(4) # ✅ Adding element print(my_list) # Output: [1, 2,
3, 4]
2️⃣Tuple Example (Immutable)
python
CopyEdit
my_tuple = (1, 2, 3) # my_tuple[0] = 10 ❌ Error (Tuples cannot be modified)
print(my_tuple) # Output: (1, 2, 3)
3️⃣Dictionary Example (Key-Value Pair)
python
CopyEdit
my_dict = {"name": "Alice", "age": 25} my_dict["age"] = 26 # ✅ Modifying value
print(my_dict) # Output: {'name': 'Alice', 'age': 26}
🚀 Conclusion:
List → Use when you need a dynamic sequence.
Tuple → Use when you need an unchangeable sequence.
Dictionary → Use when you need fast key-based access.
Recursion in Python 🌀
What is Recursion?
Recursion is a technique where a function calls itself to solve a problem by
breaking it into smaller subproblems. It continues calling itself until a base
condition is met, which stops further recursion.