0% found this document useful (0 votes)
2 views

# Lesson 6 Advanced Functions and G

Uploaded by

Steve Lee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

# Lesson 6 Advanced Functions and G

Uploaded by

Steve Lee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

# Lesson 6: Advanced Functions and Generators

# 1. Lambda Functions
print("\n--- Lambda Functions ---")
square = lambda x: x ** 2
print("Square of 5:", square(5))

# Using lambda in higher-order functions


numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print("Squared numbers:", squared_numbers)

# 2. Decorators
print("\n--- Decorators ---")
def decorator_function(func):
def wrapper():
print("Before the function call.")
func()
print("After the function call.")
return wrapper

@decorator_function
def say_hello():
print("Hello, world!")

say_hello()

# 3. Generators
print("\n--- Generators ---")
def simple_generator():
yield 1
yield 2
yield 3

gen = simple_generator()
print("First value:", next(gen))
print("Second value:", next(gen))
print("Third value:", next(gen))

# A generator for Fibonacci sequence


def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

print("Fibonacci sequence:")
for num in fibonacci(5):
print(num)

# End of Lesson 6

You might also like