Table of contents
Functions are the backbone of reusable code in Python. Today, I explored how to define and use functions effectively to write clean, modular, and efficient code.
What is a Function?
A function is a block of reusable code that performs a specific task. Instead of repeating the same logic multiple times, we define a function once and call it whenever needed.
Defining a Function in Python
In Python, we define a function using the def keyword.
#This function doesn’t take any parameters; it simply prints a message.
def greet():
print("Hello, everyone!")
Calling a Function
To execute a function, we call it by its name followed by parentheses:
greet() # Output: Hello, everyone!
Functions with Parameters
Functions become more dynamic when we pass arguments.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
Returning Values from a Function
Functions can return a result instead of just printing output.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
Default Parameters
We can set default values for function parameters.
def greet(name="Pythonista"):
print(f"Hello, {name}!")
greet() # Output: Hello, Pythonista!
greet("Emma") # Output: Hello, Emma!
Recursion in Python
Recursion is a technique where a function calls itself to solve a problem. It is especially useful for problems that can be broken down into smaller, similar subproblems.
Example: Factorial Using Recursion
The factorial of a number n is the product of all positive integers from 1 to n.
n! = n × (n-1) × (n-2) × ... × 1
Recursive Implementation
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
print(factorial(5)) # Output: 120
#WARF to calculate the sum of first n natural numbers
num = int(input("Enter a number: "))
def calc_sum_of_n_nums(num):
if(num == 0):
return 0
return calc_sum_of_n_nums(num-1) + num
print("sum is: ", calc_sum_of_n_nums(num))
#WARF to print all elements in a list. (Hint: use list and index as parameters)
values = input("Enter comma-separated values: ").split(',')
def print_all_el_ofList(given_list, index=0):
if(index == len(given_list)):
return
print(given_list[index])
print_all_el_ofList(given_list, index+1)
print_all_el_ofList(values)