๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Understand local and global variable scope
-
Recognize where variables can be accessed or modified
-
Understand the basics of recursive functions
-
Create a simple recursive function with a base condition
๐ Lesson Content
๐น Part 1: Variable Scope in Python
๐ธ What is Scope?
Scope refers to the region of a program where a variable can be accessed.
There are two main types:
-
Local Scope: Inside a function
-
Global Scope: Outside all functions
๐ธ Local Variable
Defined inside a function, only usable within that function.
๐ธ Global Variable
Defined outside any function, accessible throughout the program.
๐ธ Modifying Global Variables Inside Functions
Use the global
keyword if you want to change a global variable inside a function:
โ ๏ธ Avoid using
global
frequently โ it’s better to return values.
๐ Part 2: Recursion (Intro)
๐ธ What is Recursion?
A function that calls itself is called recursive.
Recursion helps solve problems by breaking them down into smaller parts.
๐ธ Recursive Function Structure
Base condition is important to prevent infinite loops.
โ Example: Countdown
Output:
๐ธ Example: Factorial Using Recursion
โ ๏ธ Recursion Tips
Rule | Why It’s Important |
---|---|
Always include a base case | To stop recursion (avoid infinite loop) |
Use for problems that reduce | e.g., factorial, Fibonacci, trees |
Keep input values decreasing | To reach the base condition |
๐ Assignment
-
Create a function
say_hello(n)
that prints"Hello"
n
times using recursion. -
Create a function
sum_to_n(n)
that returns the sum of numbers from1
ton
using recursion.