- Function
- Lambda Function
- Map Function
- Filter Function
- Zip Function
- *args and **kwargs
- Packing and Unpacking
- Built-in Functions
- Summary
- Tasks
Functions are blocks of code that perform a specific task. They help in organizing code and reusing it.
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!
def greet(name="User"):
print(f"Hello, {name}!")
greet("Vusal")
greet()
Output:
Hello, Vusal!
Hello, User!
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Output:
8
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
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
.
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
.
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 functions are small anonymous functions defined using the lambda
keyword.
add = lambda a, b: a + b
print(add(2, 3))
Output:
5
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}]
The map()
function applies a given function to all items in an input list.
numbers = ['1', '2', '3', '4', '5']
numbers = list(map(int, numbers))
print(numbers)
Output:
[1, 2, 3, 4, 5]
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
Output:
[2, 4, 6, 8, 10]
The filter()
function constructs an iterator from elements of an iterable for which a function returns true.
numbers = [1, 2, 3, 4, 5]
odd_numbers = list(filter(lambda x: x % 2 == 1, numbers))
print(odd_numbers)
Output:
[1, 3, 5]
The zip()
function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.
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
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
**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'}
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 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 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'}
Python provides several built-in functions for various tasks.
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
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.
- Write a function that takes a list of numbers and returns the sum of all the numbers.
- Write a lambda function that takes two numbers and returns their product.
- Use the
map()
function to convert a list of strings to a list of integers. - Use the
filter()
function to filter out even numbers from a list. - Use the
zip()
function to combine two lists into a dictionary. - Write a function that accepts any number of positional and keyword arguments and prints them.
- Use packing and unpacking to pass a list and a dictionary to a function.
- Use built-in functions to perform various tasks like finding the minimum, maximum, and sum of a list of numbers.
- Write a function to check if a number is prime.
- Write a function to calculate the factorial of a number.
- Write a function to generate the Fibonacci sequence up to
n
terms.