π§ LEGB Rule in Python (Scope Resolution)
When Python looks for a variable,
it follows a fixed order called LEGB.
L β Local
E β Enclosing
G β Global
B β Built-in
Python searches in this order.
1οΈβ£ Local Scope (L) π
Variables defined inside a function.
Output:
β€ Python finds
2οΈβ£ Enclosing Scope (E) π
Variables in outer function (nested functions).
Output:
β€ Python finds
3οΈβ£ Global Scope (G) π
Variables defined outside all functions.
Output:
β€ Python uses global
4οΈβ£ Built-in Scope (B) βοΈ
Predefined names like
Output:
π‘ Search Order
Local β Enclosing β Global β Built-in
Python stops searching once it finds the name.
When Python looks for a variable,
it follows a fixed order called LEGB.
L β Local
E β Enclosing
G β Global
B β Built-in
Python searches in this order.
1οΈβ£ Local Scope (L) π
Variables defined inside a function.
x = 10
def func():
x = 5
print(x)
func()
Output:
5β€ Python finds
x inside the function first.2οΈβ£ Enclosing Scope (E) π
Variables in outer function (nested functions).
def outer():
x = 20
def inner():
print(x)
inner()
outer()
Output:
20β€ Python finds
x in the enclosing function.3οΈβ£ Global Scope (G) π
Variables defined outside all functions.
x = 30
def func():
print(x)
func()
Output:
30β€ Python uses global
x.4οΈβ£ Built-in Scope (B) βοΈ
Predefined names like
len, print, etc.print(len([1, 2, 3]))
Output:
3π‘ Search Order
Local β Enclosing β Global β Built-in
Python stops searching once it finds the name.
β€3
π List vs Tuple in Python
Both store collections of data.
But they differ in mutability and internal behavior.
1οΈβ£ List (Mutable) π¦
Can be modified after creation.
Output:
β€ How: Stored as a dynamic array
β€ Wins: Flexible, easy to modify
β€ Risk: Slightly higher memory usage
2οΈβ£ Tuple (Immutable) π
Cannot be modified after creation.
Output:
β€ How: Fixed-size structure
β€ Wins: Faster iteration, lower memory usage
β€ Risk: No modification allowed
π‘ Key Difference
β’ List β Mutable & flexible
β’ Tuple β Immutable & lightweight
Use List when data changes.
Use Tuple when data should stay constant.
Both store collections of data.
But they differ in mutability and internal behavior.
1οΈβ£ List (Mutable) π¦
Can be modified after creation.
nums = [1, 2, 3]
nums.append(4)
print(nums)
Output:
[1, 2, 3, 4]β€ How: Stored as a dynamic array
β€ Wins: Flexible, easy to modify
β€ Risk: Slightly higher memory usage
2οΈβ£ Tuple (Immutable) π
Cannot be modified after creation.
nums = (1, 2, 3)
nums.append(4)
Output:
AttributeError: 'tuple' object has no attribute 'append'β€ How: Fixed-size structure
β€ Wins: Faster iteration, lower memory usage
β€ Risk: No modification allowed
π‘ Key Difference
β’ List β Mutable & flexible
β’ Tuple β Immutable & lightweight
Use List when data changes.
Use Tuple when data should stay constant.
β€5
π Letβs Fix How Youβre Learning Python
If you feel slow in Python, it usually is not because Python is hard. It is because of the learning approach.
Let me be direct.
β οΈ Avoid these habits
- Jumping between many tutorials
- Copying code without thinking
- Ignoring error messages
- Watching more than building
π Instead, build this discipline
- Follow one main learning path
- After every concept, write your own small code
- When an error appears, read it slowly
- Build small projects every week
π Python becomes easier the moment you start treating it like a tool, not a subject.
If you feel slow in Python, it usually is not because Python is hard. It is because of the learning approach.
Let me be direct.
β οΈ Avoid these habits
- Jumping between many tutorials
- Copying code without thinking
- Ignoring error messages
- Watching more than building
π Instead, build this discipline
- Follow one main learning path
- After every concept, write your own small code
- When an error appears, read it slowly
- Build small projects every week
π Python becomes easier the moment you start treating it like a tool, not a subject.
β€4
π§ Learn to Trace Code by Hand
Before running code, pause and predict the output. This builds real understanding.
Consider this:
Walk through slowly.
1. Start: x = 0
2. i = 0 β x = 0
3. i = 1 β x = 1
4. i = 2 β x = 3
Final output:
This habit strengthens your debugging ability more than passive reading ever will.
Try this daily with small snippets.
Before running code, pause and predict the output. This builds real understanding.
Consider this:
x = 0
for i in range(3):
x += i
print(x)
Walk through slowly.
1. Start: x = 0
2. i = 0 β x = 0
3. i = 1 β x = 1
4. i = 2 β x = 3
Final output:
3
This habit strengthens your debugging ability more than passive reading ever will.
Try this daily with small snippets.
β€5
Forwarded from Programming Quiz Channel
Which Python library is the most commonly used for numerical computing and matrix operations?
Anonymous Quiz
12%
Matplotlib
81%
NumPy
5%
Flask
2%
Seaborn
Forwarded from Programming Quiz Channel
Which Python feature allows to modify behavior of other functions?
Anonymous Quiz
50%
Decorators
26%
Iterators
20%
Generators
3%
Closures
π Python Functions (def) βοΈ
Functions help organize code into reusable blocks, making programs cleaner and more efficient. Essential for writing modular and scalable code.
π They are very important for avoiding repetitive code and building complex applications.
πΉ 1. What is a Function?
A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function.
Example:
πΉ 2. Defining & Calling a Function
We use the
Syntax:
Example:
Output:
πΉ 3. Functions with Parameters & Arguments
Parameters are variables listed inside the parentheses in the function definition. Arguments are the actual values sent when calling the function.
Example:
Output:
πΉ 4. Return Values
Functions can return data as a result using the
Example:
Output:
πΉ 5. Common Function Uses
β’ Calculations: Performing mathematical operations.
β’ Data Processing: Transforming inputs.
β’ User Interaction: Handling prompts and responses.
β’ Code Reusability: Doing the same task many times.
π― Today's Goal
βοΈ Understand what functions are
βοΈ Define and call functions
βοΈ Use parameters and arguments
βοΈ Return values from functions
π Functions are fundamental building blocks in almost every Python project.
Functions help organize code into reusable blocks, making programs cleaner and more efficient. Essential for writing modular and scalable code.
π They are very important for avoiding repetitive code and building complex applications.
πΉ 1. What is a Function?
A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function.
Example:
def greet():
print("Hello from a function!")
πΉ 2. Defining & Calling a Function
We use the
def keyword to define a function, then call it by its name.Syntax:
def function_name(parameters):
# code to execute
function_name(arguments) # call the function
Example:
def say_hello():
print("Hello, Python learner!")
say_hello() # calling the function
Output:
Hello, Python learner!πΉ 3. Functions with Parameters & Arguments
Parameters are variables listed inside the parentheses in the function definition. Arguments are the actual values sent when calling the function.
Example:
def welcome_user(name): # 'name' is a parameter
print(f"Welcome, {name}!")
welcome_user("Alice") # "Alice" is an argument
welcome_user("Bob")
Output:
Welcome, Alice!Welcome, Bob!πΉ 4. Return Values
Functions can return data as a result using the
return keyword.Example:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 7)
print(result)
Output:
12πΉ 5. Common Function Uses
β’ Calculations: Performing mathematical operations.
β’ Data Processing: Transforming inputs.
β’ User Interaction: Handling prompts and responses.
β’ Code Reusability: Doing the same task many times.
π― Today's Goal
βοΈ Understand what functions are
βοΈ Define and call functions
βοΈ Use parameters and arguments
βοΈ Return values from functions
π Functions are fundamental building blocks in almost every Python project.
β€7
Learn Python
This is Scrimba's official Python course featuring their unique interactive scrim format. It offers 58 interactive video lessons where you can pause the screencast and edit the instructor's code directly in your browser with no local setup required. Its great for hands-on learners who want to code actively during the lesson rather than passively watching. No prerequisites are required.
π 58 interactive lessons covering Python fundamentals: variables, data types, strings, lists, dictionaries, loops, functions, and file handlingβall with built-in coding challenges
β° Duration: 5.6 hours
πββοΈ Self Paced with immediate start
π Certificate: Free completion certificate included
Created by π¨βπ«: Olof Paulson & Scrimba Team
π Course Link
#Python #InteractiveLearning #FreeCertificate
Join Python Learning for more
This is Scrimba's official Python course featuring their unique interactive scrim format. It offers 58 interactive video lessons where you can pause the screencast and edit the instructor's code directly in your browser with no local setup required. Its great for hands-on learners who want to code actively during the lesson rather than passively watching. No prerequisites are required.
π 58 interactive lessons covering Python fundamentals: variables, data types, strings, lists, dictionaries, loops, functions, and file handlingβall with built-in coding challenges
β° Duration: 5.6 hours
πββοΈ Self Paced with immediate start
π Certificate: Free completion certificate included
Created by π¨βπ«: Olof Paulson & Scrimba Team
π Course Link
#Python #InteractiveLearning #FreeCertificate
Join Python Learning for more
Scrimba
Python Tutorial: Learn Python in this free course with interactive coding challenges
This 58-part tutorial will teach you Python through a mix between tutorials and interactive coding challenges.
β€5
πPython Lists (Data Structures) π¦
πΉ 1. What is a List?
A list is a sequence of values (items). They are ordered, changeable (mutable), and allow duplicate members. Defined by square brackets
Example:
Output:
πΉ 2. Accessing List Items
Items are accessed by their index, which starts at
Example:
Output:
πΉ 3. Modifying List Items
You can change an item by referring to its index.
Example:
Output:
πΉ 4. Adding Items to a List
β’
β’
Example:
Output:
πΉ 5. Removing Items from a List
β’
β’
β’
Example:
Output:
π― Today's Goal(What you should do)
βοΈ Understand what lists are and how to create them
βοΈ Access items using indexing
βοΈ Modify, add, and remove items from lists
πΉ 1. What is a List?
A list is a sequence of values (items). They are ordered, changeable (mutable), and allow duplicate members. Defined by square brackets
[].Example:
my_list = ["apple", 3.14, True, 100]
print(my_list)
Output:
['apple', 3.14, True, 100]πΉ 2. Accessing List Items
Items are accessed by their index, which starts at
0 for the first item.Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # First item
print(fruits[2]) # Third item
print(fruits[-1]) # Last item
Output:
applecherrycherryπΉ 3. Modifying List Items
You can change an item by referring to its index.
Example:
colors = ["red", "green", "blue"]
colors[1] = "yellow" # Change 'green' to 'yellow'
print(colors)
Output:
['red', 'yellow', 'blue']πΉ 4. Adding Items to a List
β’
.append(): Adds an item to the end of the list.β’
.insert(index, item): Adds an item at a specific index.Example:
names = ["Alice", "Bob"]
names.append("Charlie") # Add to end
names.insert(0, "David") # Add at the beginning
print(names)
Output:
['David', 'Alice', 'Bob', 'Charlie']πΉ 5. Removing Items from a List
β’
.remove(item): Removes the first occurrence of a specified item.β’
.pop(index): Removes (and returns) the item at a specified index (or the last item if no index is given).β’
del list[index]: Deletes the item at a specific index.Example:
numbers = [10, 20, 30, 20, 40]
numbers.remove(20) # Removes first '20'
del numbers[0] # Removes '10'
print(numbers)
Output:
[30, 20, 40]π― Today's Goal(What you should do)
βοΈ Understand what lists are and how to create them
βοΈ Access items using indexing
βοΈ Modify, add, and remove items from lists
β€8
π Python For Loops (Iteration) π
For loops are used to iterate over a sequence (like a list, tuple, string, or
π They are essential for automating tasks and processing collections of data efficiently.
πΉ 1. What is a For Loop?
A for loop executes a set of statements, once for each item in a collection.
Example:
Output:
πΉ 2. Looping Through a List
This is one of the most common uses: going through each item in a list.
Syntax:
Example:
Output:
πΉ 3. The
The
β’
β’
β’
Example:
Output:
πΉ 4.
β’
β’
Example (
Output:
Example (
Output:
π― Today's Goal(What you should do)
βοΈ Understand what for loops are
βοΈ Iterate over lists, strings, and ranges (using your Python editor)
βοΈ Use
For loops are used to iterate over a sequence (like a list, tuple, string, or
range) or other iterable objects. They let you execute a block of code repeatedly for each item.π They are essential for automating tasks and processing collections of data efficiently.
πΉ 1. What is a For Loop?
A for loop executes a set of statements, once for each item in a collection.
Example:
for character in "Python":
print(character)
Output:
PythonπΉ 2. Looping Through a List
This is one of the most common uses: going through each item in a list.
Syntax:
for item in list_name:
# code to execute for each item
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}.")
Output:
I like apple.I like banana.I like cherry.πΉ 3. The
range() FunctionThe
range() function generates a sequence of numbers, often used to loop a specific number of times.β’
range(stop): Numbers from 0 up to (but not including) stop.β’
range(start, stop): Numbers from start up to (not including) stop.β’
range(start, stop, step): Numbers from start up to stop, increasing by step.Example:
for i in range(3): # Loop 3 times (0, 1, 2)
print(f"Iteration {i}")
Output:
Iteration 0Iteration 1Iteration 2πΉ 4.
break and continue Statementsβ’
break: Stops the loop completely, even if the iterable hasn't finished.β’
continue: Skips the rest of the current iteration and moves to the next.Example (
break):for number in range(1, 6):
if number == 4:
break # Stop when number is 4
print(number)
Output:
123Example (
continue):for item in ["A", "B", "C", "D"]:
if item == "C":
continue # Skip 'C'
print(item)
Output:
ABDπ― Today's Goal(What you should do)
βοΈ Understand what for loops are
βοΈ Iterate over lists, strings, and ranges (using your Python editor)
βοΈ Use
break and continue to control loop flow (using your Python editor)β€6π₯2
π Python If-Else Statements (Conditionals) π€
If-Else statements allow your program to make decisions and execute different code blocks based on conditions. They are fundamental for creating dynamic and responsive applications.
π Essential for controlling the flow of your program.
πΉ 1. What are Conditional Statements?
They test a condition. If the condition is
Example:
Output:
πΉ 2. The
The simplest conditional, executing code only when a condition is
Syntax:
Example:
Output:
πΉ 3. The
Executes a block of code when the
Syntax:
Example:
Output:
πΉ 4. The
Allows you to check multiple conditions sequentially. If the first
Syntax:
Example:
Output:
πΉ 5. Short Hand If / Ternary Operator
A concise way to write simple
Example:
Output:
π― Today's Goal(What you should do)
βοΈ Understand how to use
βοΈ Make your programs respond to different inputs
βοΈ Use shorthand for simple conditions
π Conditional statements are the backbone of any interactive and logical Python program. It's crucial you understand them well.
If-Else statements allow your program to make decisions and execute different code blocks based on conditions. They are fundamental for creating dynamic and responsive applications.
π Essential for controlling the flow of your program.
πΉ 1. What are Conditional Statements?
They test a condition. If the condition is
True, one block of code runs. If False, another block (or nothing) might run.Example:
temperature = 25
if temperature > 20:
print("It's warm!")
Output:
It's warm!πΉ 2. The
if StatementThe simplest conditional, executing code only when a condition is
True.Syntax:
if condition:
# code to run if condition is True
Example:
age = 18
if age >= 18:
print("You are an adult.")
Output:
You are an adult.πΉ 3. The
else StatementExecutes a block of code when the
if condition is False.Syntax:
if condition:
# code if True
else:
# code if False
Example:
score = 75
if score >= 90:
print("Excellent!")
else:
print("Good effort!")
Output:
Good effort!πΉ 4. The
elif (Else If) StatementAllows you to check multiple conditions sequentially. If the first
if is False, it checks elif, and so on.Syntax:
if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True
else:
# code if all conditions are False
Example:
time = 14
if time < 12:
print("Good morning!")
elif time < 18:
print("Good afternoon!")
else:
print("Good evening!")
Output:
Good afternoon!πΉ 5. Short Hand If / Ternary Operator
A concise way to write simple
if-else statements on a single line.Example:
a = 10
b = 5
print("A is greater") if a > b else print("B is greater")
Output:
A is greaterπ― Today's Goal(What you should do)
βοΈ Understand how to use
if, elif, and elseβοΈ Make your programs respond to different inputs
βοΈ Use shorthand for simple conditions
π Conditional statements are the backbone of any interactive and logical Python program. It's crucial you understand them well.
β€4
Forwarded from Programming Quiz Channel
Which Python keyword allows defining anonymous functions?
Anonymous Quiz
24%
func
66%
lambda
7%
inline
3%
quick
β€4