Skip to content

Functions

1
2
3
4
5
6
7
8
9
def print_numbers(*args, **kwargs):
    print(type(args))
    print("args:", args)

    print(type(kwargs))
    print("kwargs:", kwargs)


print_numbers(1, 2, 3, 4, 5, 6, name="John", age=30, city="New York")

args: (1, 2, 3, 4, 5, 6)

kwargs: {'name': 'John', 'age': 30, 'city': 'New York'}

print("return multiple values from a function")


def return_multiple_values():
    return 1, 2, 3


result = return_multiple_values()
print(type(result))
print("Result:", result)

a, b, c = return_multiple_values()
print("a:", a)
print("b:", b)
print("c:", c)

return multiple values from a function

Result: (1, 2, 3)

a: 1

b: 2

c: 3

def is_strong_password(password):
    if len(password) < 8:
        return False
    if not any(char.isdigit() for char in password):
        return False
    if not any(char.isupper() for char in password):
        return False
    if not any(char.islower() for char in password):
        return False
    if not any(char in "!@#$%^&*()-_=+[]{}|;:,.<>?/" for char in password):
        return False
    return True


print("Is 'Password123' a strong password?", is_strong_password("Password123"))

Is 'Password123' a strong password? False

1
2
3
4
5
6
7
def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]


print("Is 'race car' a palindrome?", is_palindrome("race car"))
print("Is 'hello' a palindrome?", is_palindrome("hello"))

Is 'race car' a palindrome? True

Is 'hello' a palindrome? False

print("Recursive function example: Factorial")


def factorial(n):
    print(n)
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)


print("Factorial of 5:", factorial(5))

Recursive function example: Factorial

5

4

3

2

1

Factorial of 5: 120

Lambda function

A lambda function is an anonymous function (a function without a name)

1
2
3
addition = lambda x, y: x + y
print(type(addition))
addition(5, 3)

8

Map function

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
list(map(lambda x: x**2, numbers))

[1, 4, 9, 16, 25, 36, 49, 64]

1
2
3
4
print("Map function with two lists")
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
list(map(lambda x, y: x + y, numbers1, numbers2))

Map function with two lists

[5, 7, 9]

words = ["hello", "world", "python"]
list(map(str.upper, words))

['HELLO', 'WORLD', 'PYTHON']

1
2
3
4
5
6
7
people = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35},
]

list(map(lambda person: person["name"], people))

['Alice', 'Bob', 'Charlie']

Filter

numbers = [1, 2, 3, 4, 5]
list(filter(lambda x: x % 2 == 0, numbers))

[2, 4]