Skip to content

Latest commit

 

History

History
441 lines (317 loc) · 8.25 KB

README.md

File metadata and controls

441 lines (317 loc) · 8.25 KB

Chapter 6: Functions

Table of Contents

Function

Functions are blocks of code that perform a specific task. They help in organizing code and reusing it.

Defining a Function

def greet_user():
    print("Welcome to the program!")
    print("We hope you have a great time here.")
    print("Have a nice day!")

greet_user()

Output:

Welcome to the program!
We hope you have a great time here.
Have a nice day!

Function with Parameters

def greet(name="User"):
    print(f"Hello, {name}!")

greet("Vusal")
greet()

Output:

Hello, Vusal!
Hello, User!

Function with Return Value

def add(a, b):
    return a + b

result = add(5, 3)
print(result)

Output:

8

Example: Prime Number Check

def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            return "Composite"
    return "Prime"

number = int(input("Enter a number: "))
print(is_prime(number))

Output:

Enter a number: 7
Prime

Example: Prime Number Check

A function to check if a number is prime.

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

number = int(input("Enter a number: "))
print(f"{number} is {'a prime number' if is_prime(number) else 'not a prime number'}")

Output:

Enter a number: 7
7 is a prime number

Explanation: The function is_prime checks if a number is prime by iterating from 2 to the square root of the number. If any number divides n evenly, it returns False. Otherwise, it returns True.

Example: Factorial Calculation

A function to calculate the factorial of a number.

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

number = int(input("Enter a number: "))
print(f"The factorial of {number} is {factorial(number)}")

Output:

Enter a number: 5
The factorial of 5 is 120

Explanation: The function factorial calculates the factorial of a number using recursion. If n is 0 or 1, it returns 1. Otherwise, it multiplies n by the factorial of n-1.

Example: Fibonacci Sequence

A function to generate the Fibonacci sequence up to n terms.

def fibonacci(n):
    sequence = []
    a, b = 0, 1
    while len(sequence) < n:
        sequence.append(a)
        a, b = b, a + b
    return sequence

terms = int(input("Enter the number of terms: "))
print(f"Fibonacci sequence up to {terms} terms: {fibonacci(terms)}")

Output:

Enter the number of terms: 7
Fibonacci sequence up to 7 terms: [0, 1, 1, 2, 3, 5, 8]

Explanation: The function fibonacci generates the Fibonacci sequence up to n terms by iterating and appending the values to a list. It starts with a and b as 0 and 1, respectively, and updates them in each iteration.

Lambda Function

Lambda functions are small anonymous functions defined using the lambda keyword.

Basic Lambda Function

add = lambda a, b: a + b
print(add(2, 3))

Output:

5

Example: Sorting with Lambda

people = [
    {'name': 'Emin', 'age': 20},
    {'name': 'Günay', 'age': 30},
    {'name': 'Cavid', 'age': 23},
    {'name': 'Elvin', 'age': 54},
    {'name': 'Leyla', 'age': 42}
]

people.sort(key=lambda x: x['age'])
print(people)

Output:

[{'name': 'Emin', 'age': 20}, {'name': 'Cavid', 'age': 23}, {'name': 'Günay', 'age': 30}, {'name': 'Leyla', 'age': 42}, {'name': 'Elvin', 'age': 54}]

Map Function

The map() function applies a given function to all items in an input list.

Basic Map Function

numbers = ['1', '2', '3', '4', '5']
numbers = list(map(int, numbers))
print(numbers)

Output:

[1, 2, 3, 4, 5]

Example: Doubling Numbers

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

Output:

[2, 4, 6, 8, 10]

Filter Function

The filter() function constructs an iterator from elements of an iterable for which a function returns true.

Basic Filter Function

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

Output:

[1, 3, 5]

Zip Function

The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

Basic Zip Function

names = ['Ilqar', 'Namiq', 'Nazim', 'Vuqar', 'Malik']
ages = [20, 16, 25, 33, 27]

people = dict(zip(names, ages))
print(people)

Output:

{'Ilqar': 20, 'Namiq': 16, 'Nazim': 25, 'Vuqar': 33, 'Malik': 27}

*args and **kwargs

Using *args

*args allows you to pass a variable number of arguments to a function.

def add(*args):
    result = 0
    for num in args:
        result += num
    return result

print(add(2, 5, 6, 10, 15))

Output:

38

Using **kwargs

**kwargs allows you to pass keyworded variable length of arguments to a function.

def print_info(**kwargs):
    print(kwargs)

print_info(name="Vusal", surname="Huseynov")

Output:

{'name': 'Vusal', 'surname': 'Huseynov'}

Combining *args and **kwargs

def func(x, y, *args, **kwargs):
    print(x, y)
    print(args)
    print(kwargs)

func(1, 2, 3, a=5, b=10, c=5)

Output:

1 2
(3,)
{'a': 5, 'b': 10, 'c': 5}

Packing and Unpacking

Packing

Packing is the process of combining multiple values into a single variable.

def func(*args):
    print(args)

l = [1, 2, 3]
func(*l, 4, 5)

Output:

(1, 2, 3, 4, 5)

Unpacking

Unpacking is the process of extracting values from a packed variable.

def func(**kwargs):
    print(kwargs)

d = {"name": "Vusal", "surname": "Huseynov"}
func(**d)

Output:

{'name': 'Vusal', 'surname': 'Huseynov'}

Built-in Functions

Python provides several built-in functions for various tasks.

Example: Using Built-in Functions

from math import floor

t = list((1, 2, 3, 4, 5))
d = dict([(str(i) + '.', i) for i in t])

print(abs(-10))  # Absolute value
print(bin(10))   # Binary representation
print(hex(10))   # Hexadecimal representation
print(round(5.5))  # Rounding
print(chr(97))   # Character from ASCII
print(ord('A'))  # ASCII value of character
print(floor(5.9))  # Floor value
print(divmod(5, 2))  # Division and modulus
print(pow(5, 3))  # Power
print(eval("5 + 5"))  # Evaluate expression
print(list(enumerate(['A', 'B', 'C'])))  # Enumerate
print(oct(100))  # Octal representation
print(sum([1, 2, 3, 4]))  # Sum
print(min([10, 5, 16]))  # Minimum
print(max([10, 5, 16]))  # Maximum

Output:

10
0b1010
0xa
6
a
65
5
(2, 1)
125
10
[(0, 'A'), (1, 'B'), (2, 'C')]
0o144
10
5
16

Summary

In this chapter, we covered functions, lambda functions, map and filter functions, zip function, *args and **kwargs, packing and unpacking, and built-in functions. We also provided examples for checking if a number is prime, calculating the factorial of a number, and generating the Fibonacci sequence.

Tasks

  1. Write a function that takes a list of numbers and returns the sum of all the numbers.
  2. Write a lambda function that takes two numbers and returns their product.
  3. Use the map() function to convert a list of strings to a list of integers.
  4. Use the filter() function to filter out even numbers from a list.
  5. Use the zip() function to combine two lists into a dictionary.
  6. Write a function that accepts any number of positional and keyword arguments and prints them.
  7. Use packing and unpacking to pass a list and a dictionary to a function.
  8. Use built-in functions to perform various tasks like finding the minimum, maximum, and sum of a list of numbers.
  9. Write a function to check if a number is prime.
  10. Write a function to calculate the factorial of a number.
  11. Write a function to generate the Fibonacci sequence up to n terms.

Next Chapter: Object-Oriented Programming and Modules