A function is a block of code that performs a specific task. Functions only run when they are called. They help reduce code duplication and complexity.
- Functions can accept data as parameters.
- Functions can return results.
- Functions reduce the need for duplicate code.
def function_name(parameters):
# Block of statementsdef calc_sum(a, b): # a, b are parameters
sum = a + b
print("Sum of two numbers is:", sum)
# Function call with arguments
calc_sum(10, 20)def print_hello():
print("Hello World")
print_hello()def average(a, b, c):
avg = (a + b + c) / 3
print(avg)
average(1, 2, 3)- Examples:
print(),input(),len(),sum(),max(),min()
Functions created by users to perform specific tasks.
def calc_sum(a, b):
sum = a + b
return sum
result = calc_sum(10, 20)
print(result)def cal_prod(a, b=1):
print(a * b) # Multiplication of two numbers
return a * b
cal_prod(5)cities = ["dhaka", "mumbai", "delhi", "kolkata"]
def print_length(lst):
print(len(lst))
print_length(cities)cities = ["dhaka", "mumbai", "delhi", "kolkata"]
def print_elements(lst):
for i in lst:
print(i, end=" ")
print_elements(cities)def factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
print(fact)
factorial(5)def converter(usd):
bdt = 121.75 * usd
print(bdt)
converter(100)def check_num(n):
if n % 2 == 0:
return "even"
else:
return "odd"
print(check_num(5))
print(check_num(6))