Back to Module 4

More about functions

Functions help you avoid repeating code. See the earlier functions lesson in 2-3.md.

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

Safe division

def safe_divide(a, b):
    if b == 0:
        return None
    return a / b

Palindrome checker

def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

Lambda example

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares)

Next: Classes