Let us begin by going over the fundamentals of Python programming functions before advancing to more complex ideas.

Learn Python Programming functions with examples and explanations
Functions in Python:
What are Functions in Python programming?
A function is a block of organized, reusable code that performs a specific task. It takes inputs (arguments), processes them, and returns outputs. Functions provide modularity to your code, making it easier to understand, reuse, and maintain.
Why are Functions Used?
- Modularity: Functions allow you to break down a complex problem into smaller, manageable pieces. Each function handles a specific task, promoting code reusability and maintainability.
- Abstraction: Functions hide the implementation details of a particular task. You can use a function without needing to know how it works internally, focusing only on its inputs and outputs.
- Code Organization: Functions help in organizing your code logically. Instead of writing a monolithic script, you can structure your code into smaller, meaningful functions, improving readability and debugging.
- Debugging and Testing: With functions, you can isolate specific parts of your code for testing and debugging. This makes it easier to identify and fix errors.
- Scoping: Functions introduce scope in Python, which means variables defined inside a function are only accessible within that function (unless explicitly specified otherwise). This helps prevent naming conflicts and unintended side effects.
- Code Reusability: Once you’ve written a function to perform a certain task, you can reuse it multiple times throughout your program or even in other programs, saving time and effort.
How to Define and Use Functions in Python:
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
# output: Hello, Alice!
In this example, greet is a function that takes one parameter (name) and returns a greeting message. When called with "Alice", it returns "Hello, Alice!".
Remember:
- Functions are defined using the
defkeyword followed by the function name and parameters in parentheses. - The function body is indented and contains the code to perform the task.
- You can add an optional docstring (enclosed in triple quotes) to describe what the function does.
- Use the
returnstatement to specify the value(s) to be returned by the function. - To call a function, simply use its name followed by parentheses, passing any required arguments.
Here are 30 examples that cover various aspects of Python functions, from basic usage to more advanced concepts like decorators and generators. Experiment with them to deepen your understanding!
I. Function without Parameters:
The provided code defines a function named greet that generates a greeting message, specifically “Hello Planet!”.
def greet():
return "Hello Planet!"
# Calling the function
print(greet())
# output: Hello Planet!
Here’s how it works:
- Function Definition:
def greet(): This function does not take any parameters.
- Greeting Generation:
- Inside the function, it directly returns the string “Hello Planet!”.
- Calling the Function:
print(greet()): This line calls thegreetfunction without any arguments. The function is invoked, and its return value, “Hello Planet!”, is printed to the console.
- Output:
- The output of the
printstatement will be “Hello Planet!”, as the functiongreetreturns this string when called.
- The output of the
II. Function with Parameters:
The provided code defines a function named greet that generates a greeting message for a person by their name.
def greet(name):
return f"Hello, {name}!"
# call the function
print(greet("Alice"))
# output: Hello, Alice!
Here’s how it works:
- Function Definition:
def greet(name): This function takes one parametername, representing the name of the person to be greeted.
- Greeting Generation:
- Inside the function, it generates a greeting message using f-string formatting, where
{name}is replaced by the providednameparameter.
- Inside the function, it generates a greeting message using f-string formatting, where
- Calling the Function:
print(greet("Alice")): This line calls thegreetfunction with the argument"Alice". The function then generates and prints the greeting message “Hello, Alice!”.
- Output:
- The output of the
printstatement will be “Hello, Alice!”, as the function is called with the argument"Alice", which is used to generate the greeting message.
- The output of the
III. Function with the Default Parameter:
This code defines a function named greet that greets a person by their name, with a default greeting for “World” if no name is provided.
def greet(name="World"):
return f"Hello, {name}"
# call the function
print(greet()) # output: Hello, World
print(greet("Alice")) # output: Hello, Alice
def greet(name="World"):This line defines a function namedgreetwith one parametername. The parameternamehas a default value of"World", meaning if no argument is passed when calling the function,"World"will be used as the value forname.return f"Hello, {name}!": Inside the function, it constructs a greeting message using f-string formatting. If a value is provided forname, it will be used; otherwise,"World"(the default value) will be used. The constructed message is then returned by the function.
greet(): This line calls thegreetfunction without providing any argument. Since no argument is provided, the default value"World"is used for thenameparameter. The function returns"Hello, World!", which is then printed.greet("Alice"): This line calls thegreetfunction with"as the argument. The function overrides the default value ofAlice"namewith", and the function returnsAlice""Hello,, which is then printed.Alice!"
- The first
printstatement prints"Hello, World!"because no argument is provided, so the default value"World"is used. - The second
printstatement prints"Hello,because!"Alice"is provided as an argument, overriding the default value."Alice
IV. Function with Multiple Parameters:
The provided code defines a function named add that computes the sum of two numbers a and b.
def add(a,b):
return a + b
# Call the function
print(add(3,5))
Here’s how it works:
- Function Definition:
def add(a, b): This function takes two parametersaandb.
- Sum Calculation:
- Inside the function, it computes the sum of
aandbusing the addition operator (+).
- Inside the function, it computes the sum of
- Calling the Function:
print(add(3, 5)): This line calls theaddfunction witha = 3andb = 5.- The function adds the two numbers
3and5, resulting in8.
- Output:
- The output will be the result of the addition operation, which is
8in this case.
- The output will be the result of the addition operation, which is
V. Function with Multiple Return Values:
This code defines a function called square_and_cube that takes one parameter x. Inside the function, it calculates the square of x and the cube of x using the exponentiation operator (**). The function returns both the square and the cube as a tuple (x ** 2, x ** 3).
def square_and_cube(x):
return x ** 2, x ** 3
# Call the fuction
sq, cb = square_and_cube(3)
print(sq) # output: 9
print(cb) # output: 27
Then, the function is called with the argument 3, and the returned values are unpacked into variables sq and cb. Finally, it prints sq, which represents the square of 3, and cb, which represents the cube of 3. The output is 9 for the square and 27 for the cube.
VI. Function with Variable Number of Arguments (Arbitrary Arguments):
This code defines a function named average that takes a variable number of arguments (*args). Inside the function, it calculates the average of the provided arguments by summing them up (sum(args)) and dividing by the number of arguments (len(args)). If no arguments are provided (if args evaluates to False), it returns 0 to avoid division by zero.
Then, the function is called twice:
average(2, 3, 4): It calculates the average of the numbers2,3, and4, which is3.0, and prints it.average(10, 20, 30): It calculates the average of the numbers10,20, and30, which is20.0, and prints it.
def average(*args):
return sum(args) / len(args) if args else 0
# Call the function
print(average(2,3,4))
print(average(10,20,30))
Note:
In Python, the asterisk (*) before a parameter name, such as *args, is used to indicate that the function can accept a variable number of positional arguments. Here’s how it works:
- Variable Number of Arguments:
- When you use
*argsas a parameter in a function definition, it allows the function to accept any number of positional arguments. - These arguments are collected into a tuple named
argsinside the function. This tuple contains all the positional arguments passed to the function.
- When you use
- Flexibility:
- Using
*argsprovides flexibility because you can call the function with any number of arguments, including zero. - It allows you to define functions that can operate on a variable number of inputs without needing to specify them individually.
- Using
def my_function(*args):
for arg in args:
print(arg)
my_function(1, 2, 3) # Output: 1 2 3
my_function('a', 'b') # Output: a b
my_function() # Output: (no output, as no arguments are passed)
Use Cases:
- When you’re not sure how many arguments will be passed to the function.
- When you want to create a generic function that can operate on different numbers of inputs.
- When you want to pass a variable number of arguments to another function within your function.
VII. Function with Keyword Arguments:
Keyword arguments allow you to specify arguments by parameter name, regardless of their order.
def person_info(name, age):
return f"Name: {name}, Age: {age}"
# Call the function
print(person_info(age=30, name="Alice"))
Here’s how it works:
This code defines a function named person_info that takes two parameters: name and age. Inside the function, it constructs a string containing information about the person’s name and age using f-string formatting.
Then, the function is called with named arguments:
age=30: This assigns the value30to theageparameter.name="Alice": This assigns the value"Alice"to thenameparameter.
Even though the order of the arguments is different from the function definition, the function is called using named arguments, so the order doesn’t matter.
This demonstrates how named arguments can be used to call a function in Python, allowing for more readable and flexible function calls.
VIII. Function with Default and Arbitrary Arguments:
The provided code defines a function named describe_person that generates a description of a person with their name, age, and additional optional attributes provided as keyword arguments (kwargs).
def describe_person(name, age=25, **kwargs):
info = f"Name: {name}, Age: {age}"
for key, value in kwargs.items():
info += f", {key}: {value}"
return info
# Call the function
print(describe_person("Bob",job="Engineer"))
- Function Definition:
def describe_person(name, age=25, **kwargs): This function takes three parameters:name(mandatory),age(optional with a default value of25), and**kwargs(arbitrary keyword arguments).
- Description Generation:
- Inside the function, a string variable
infois initialized with the person’s name and age. - Then, a loop iterates over the arbitrary keyword arguments (
kwargs) provided to the function. - For each keyword argument, the key-value pair is appended to the
infostring, separated by a comma and space.
- Inside the function, a string variable
- Returning the Description:
- The function returns the
infostring, which contains the person’s name, age, and any additional attributes provided as keyword arguments.
- The function returns the
- Calling the Function:
print(describe_person("Bob", job="Engineer")): This line calls thedescribe_personfunction with the name"Bob"and the additional keyword argumentjob="Engineer".- The function generates a description of the person with the provided information and any additional attributes.
- The resulting description is then printed to the console.
- Output:
- The output will be the description of the person, including their name, age, and job (if provided as a keyword argument).
- For example,
"Name: Bob, Age: 25, job: Engineer".
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
my_function(name="Alice", age=30, city="New York")
Arbitrary keyword arguments:
Arbitrary keyword arguments in Python functions refer to the ability to accept an arbitrary number of keyword arguments in a function call. This is achieved by using the double asterisk (**) before a parameter in the function definition.
Syntax:
def my_function(**kwargs):
# Function body
Here’s a breakdown:
- The parameter
**kwargsstands for “keyword arguments” and collects all the keyword arguments passed to the function into a dictionary. - Each keyword argument consists of a key-value pair, where the key is the parameter name and the value is the argument value.
- Inside the function, you can access these keyword arguments using dictionary syntax (
kwargs[key]).
IX. Function with Docstring:
This code defines a function named greet that takes one parameter name. The function returns a greeting message using the provided name.
def greet(name):
"""Function to greet a person by name"""
return f"Hello, {name}"
# Access the docstring
print(greet.__doc__)
Here’s a breakdown:
- Function Definition:
def greet(name): This function takes a single parametername, representing the name of the person to greet.
- Docstring:
"""Function to greet a person by name""": This is a docstring, enclosed within triple quotes ("""). It provides a brief description of the function’s purpose, which is to greet a person by name.
- Return Statement:
return f"Hello, {name}": This line returns a formatted string that greets the person by interpolating their name into the greeting message.
- Accessing the Docstring:
print(greet.__doc__): This line accesses the docstring of thegreetfunction using the special attribute__doc__.- The
__doc__attribute contains the docstring associated with the function, and it is printed to the console.
- Output:
- The output will be the docstring text:
"Function to greet a person by name", as it describes the purpose of thegreetfunction.
- The output will be the docstring text:
X. Recursive Function:
This code defines a recursive function named factorial to compute the factorial of a non-negative integer n.
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
# Call the function
print(factorial(5))
Here’s how it works:
- Function Definition:
def factorial(n): This function takes an integernas input.
- Base Case and Recursion:
- The function uses recursion to compute the factorial of
n. - The base case of the recursion is when
nequals0. In this case, the function returns1, as the factorial of0is1. - If
nis not0, the function recursively calls itself with the argumentn-1and multiplies the result byn.
- The function uses recursion to compute the factorial of
- Calling the Function:
print(factorial(5)): This line calls thefactorialfunction with5as the argument.- The function recursively computes the factorial of
5, which is5 * 4 * 3 * 2 * 1, and returns the result.
- Output:
- The output will be the factorial of
5, which is120.
- The output will be the factorial of
XI. Anonymous Function (Lambda Function):
This code demonstrates the use of lambda functions in Python to create an anonymous function that doubles its input.This code demonstrates the use of lambda functions in Python to create an anonymous function that doubles its input.
double = lambda x: x * 2
# Call the function
print(double(5))
Here’s a breakdown of the code:
- Lambda Function Definition:
double = lambda x: x * 2: This line defines a lambda function that takes a single parameterxand returnsx * 2, effectively doubling the value ofx.- Lambda functions are anonymous functions defined using the
lambdakeyword, allowing for quick creation of simple functions without the need for a formaldefstatement.
- Calling the Lambda Function:
print(double(5)): This line calls the lambda function stored in the variabledoublewith the argument5.- The lambda function doubles the input value
5, resulting in10. - The result,
10, is then printed to the console.
XII. Function as a Parameter:
This code demonstrates the use of higher-order functions in Python, specifically by defining two functions: square and apply.
def square(x):
return x ** 2
def apply(func, n):
return func(n)
# Call the function
print(apply(square, 3))
Here’s a breakdown of the code:
squareFunction:def square(x): This function takes a single parameterxand returns the square ofxusing the exponentiation operator (**).
applyFunction:def apply(func, n): This function takes two parameters:func, which represents another function, andn, which is a value to be passed to the functionfunc.- Inside the
applyfunction, it calls the functionfuncwith the argumentnand returns the result.
- Calling the
applyFunction:print(apply(square, 3)): This line calls theapplyfunction withsquareas the function argument and3as the value to be squared.- The
applyfunction calls thesquarefunction with3as the argument, which computes the square of3. - The result, which is
9(the square of3), is then printed to the console.
XIII. Function Returning Function:
This function returns another function.
def get_multiplies(n):
def multiplier(x):
return x * n
return multiplier
# Call the function
times3 = get_multiplies(3)
print(times3(5))
Here’s how it works:
This code defines a function called get_multiplies that takes a parameter n. Inside get_multiplies, another nested function multiplier is defined, which takes a parameter x and returns the result of x * n.
When get_multiplies is called with an argument, say 3, it returns the nested multiplier function with n set to 3. This returned function is assigned to the variable times3.
Finally, times3 is called with an argument 5, which applies the nested multiplier function with n=3 to x=5, resulting in 5 * 3 = 15. The result, 15, is printed to the console.
In essence, get_multiplies returns a function that can multiply its argument by the value of n passed to get_multiplies, allowing for the creation of customized multiplication functions.
XIV. Decorator Function:
Decorators are functions that modify the behavior of another function.
def decoder(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
def greet():
print("Hello!")
# Call the function
greet()
Here’s how it works:
decoder(func): This function takes another functionfuncas an argument. Insidedecoder, a nested functionwrapperis defined.wrapperprints “Before function execution”, then calls the original functionfunc, and finally prints “After function execution”.wrapperis then returned bydecoder.greet(): This is a simple function that prints “Hello!”.
When greet() is called directly, it prints “Hello!” to the console.
The decoder function allows us to modify the behavior of greet() by wrapping it inside another function. However, in the provided code, the decoder function is defined but not used to modify the behavior of greet(). Thus, when greet() is called directly, it simply prints “Hello!” without any additional behavior before or after its execution.
XV. Generator Function:
Generator functions allow you to generate a sequence of values over time.
def countdown(n):
while n > 0:
yield n
n -= 1
# Call the function
for i in countdown(5):
print(i)
Here’s how it works:
- Function Definition:
def countdown(n):: This line defines thecountdownfunction that takes one parametern.
- Generator Logic:
while n > 0:: This while loop continues as long asnis greater than 0.yield n: Inside the loop, the current value ofnis yielded (returned) by the generator, allowing the caller to access it without terminating the function’s execution.n -= 1: The value ofnis decremented by 1 in each iteration of the loop.
- Function Call:
for i in countdown(5):: This line calls thecountdownfunction with5as the starting point.forloop iterates over the values yielded by thecountdowngenerator, assigning each value toi.- Inside the loop, each yielded value (
n) is printed.
- Output:
- The loop prints the numbers generated by
countdown(5)in reverse order, starting from5and counting down to1.
- The loop prints the numbers generated by
XVI. Function with Annotations:
Annotations provide metadata about the types of function parameters and return value.
This code defines a function named add that takes two parameters a and b, both of which are annotated as int (integer types), and specifies that the return type of the function is also int.
Annotations in Python are used to provide additional information about the types of parameters and return values of functions, but they do not enforce type checking at runtime. They serve as documentation and can be accessed using the __annotations__ attribute of the function.
The print(add.__annotations__) statement accesses the annotations of the add function and prints them to the console.
def add(a: int, b: int) -> int:
return a+b
# Access the annotations
print(add.__annotations__)
output:
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
XVII. Function to Filter Odd Numbers:
This function filters out the odd numbers from a list.
This code defines a function named filter_odd that takes a list of numbers as input. Inside the function, it creates a new list using a list comprehension that includes only the numbers from the input list that are odd (i.e., have a remainder of 1 when divided by 2).
Then, it calls the filter_odd function with the list [1, 2, 3, 4, 5, 6, 7]. The function filters out the odd numbers from the input list and returns a new list containing only the odd numbers.
Finally, the resulting list [1, 3, 5, 7] is printed to the console.
In summary, the function filter_odd filters out the odd numbers from a given list and returns a new list containing only those odd numbers.
def filter_odd(numbers):
return[num for num in numbers if num % 2 != 0]
# Call the function
print(filter_odd([1,2,3,4,5,6,7]))
# output: [1, 3, 5, 7]
XVIII. Function to Map Square of Numbers:
This function maps the square of numbers in a list.
This code defines a function named square_numbers that takes a list of numbers as input. Inside the function, it creates a new list using a list comprehension. For each number num in the input list, it calculates its square (num ** 2) and adds it to the new list.
Then, it calls the square_numbers function with the list [1, 2, 3, 4, 5, 6]. The function calculates the square of each number in the input list and returns a new list containing the squared numbers.
Finally, the resulting list [1, 4, 9, 16, 25, 36] is printed to the console.
def square_numbers(numbers):
return [num ** 2 for num in numbers]
# Call the function
print(square_numbers([1,2,3,4,5,6]))
# output: [1, 4, 9, 16, 25, 36]
XIX. Function to Reduce a List to a Single Value:
This function reduces a list of numbers to a single value by multiplying them together.
from functools import reduce
def multiply(numbers):
return reduce(lambda x,y: x*y, numbers)
# Call the function
print(multiply([1,2,3,4,5]))
Here’s how it works:
- Importing the
reduceFunction:from functools import reduce: This line imports thereducefunction from thefunctoolsmodule.
- Defining the
multiplyFunction:def multiply(numbers): This function takes a list of numbers as input.- Inside the function, the
reducefunction is used with a lambda function to multiply all the numbers together. - The lambda function takes two arguments
xandyand returns their product (x * y). - The
reducefunction then applies this lambda function cumulatively to the elements of the input list, resulting in the product of all the numbers.
- Calling the Function:
print(multiply([1,2,3,4,5])): This line calls themultiplyfunction with the list[1, 2, 3, 4, 5].- The function calculates the product of all the numbers in the list and prints the result.
- Output:
- The output will be the product of all the numbers in the list, which is
120in this case (1 * 2 * 3 * 4 * 5).
- The output will be the product of all the numbers in the list, which is
XX. Function to Find the Maximum Element:
This function finds the maximum element in a list.
This code defines a function named find_max that takes a list of numbers as input. Inside the function, it uses the built-in max() function to find the maximum value among the numbers in the input list.
def find_max(numbers):
return max(numbers)
# Call the function
print(find_max([2,1,55,44,8,56,45,54]))
Here’s how it works:
- Defining the
find_maxFunction:def find_max(numbers): This function takes a list of numbers as input.
- Finding the Maximum Value:
- Inside the function, the
max()function is used with the input listnumbersas its argument. - The
max()function returns the largest value from the list.
- Inside the function, the
- Calling the Function:
print(find_max([2,1,55,44,8,56,45,54])): This line calls thefind_maxfunction with the list[2,1,55,44,8,56,45,54].- The function finds the maximum value from the list and prints it.
- Output:
- The output will be the maximum value from the list, which is
56in this case.
- The output will be the maximum value from the list, which is
XXI. Function to Find Minimum Element:
This function finds the minimum element in a list.
This code defines a function named find_min that takes a list of numbers as input. Inside the function, it uses the built-in min() function to find the minimum value among the numbers in the input list.
def find_min(numbers):
return min(numbers)
# Call the function
print(find_min([2,1,55,44,8,56,45,54]))
Here’s how it works:
- Defining the
find_minFunction:def find_min(numbers): This function takes a list of numbers as input.
- Finding the Minimum Value:
- Inside the function, the
min()function is used with the input listnumbersas its argument. - The
min()function returns the smallest value from the list.
- Inside the function, the
- Calling the Function:
print(find_min([2,1,55,44,8,56,45,54])): This line calls thefind_minfunction with the list[2,1,55,44,8,56,45,54].- The function finds the minimum value from the list and prints it.
- Output:
- The output will be the minimum value from the list, which is
1in this case.
- The output will be the minimum value from the list, which is
XXII. Function to Check if a Number is Prime:
This code defines a function named is_prime that checks whether a given number n is prime or not. Here’s a brief explanation of how it works:
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
# Call the function
print(is_prime(11))
Here’s how it works:
- Function Definition:
def is_prime(n): This function takes an integernas input.
- Checking for Non-Prime Conditions:
- The function first checks if the input number
nis less than or equal to1. If it is, it returnsFalse, as numbers less than or equal to1are not considered prime.
- The function first checks if the input number
- Iterating for Prime Check:
- If
nis greater than1, the function iterates over a range starting from2up to the square root ofn(inclusive). - For each number
iin this range, it checks ifnis divisible evenly byi. If it is,nis not prime, so the function returnsFalse. - If no divisors are found in the loop, the function returns
True, indicating thatnis prime.
- If
- Calling the Function:
print(is_prime(11)): This line calls theis_primefunction with the number11.- The function checks whether
11is prime or not and prints the result.
- Output:
- Since
11is a prime number, the function returnsTrue, and the output will beTrue.
- Since
XXIII. Function to Check if a String is Palindrome:
This function checks if a string is a palindrome.
def is_palindrome(s):
return s == s[::-1]
# Call the function
print(is_palindrome("radar"))
Here’s how it works:
- The word “radar” is a palindrome because it reads the same forwards and backwards.
- The phrase “A man, a plan, a canal, Panama” is a palindrome because, after removing spaces and punctuation, it reads the same forwards and backwards.
- The number “12321” is a palindrome because its digits read the same forwards and backwards.
Palindrome: A palindrome is a word, phrase, number, or other sequence of characters that reads the same forwards and backwards. In other words, if you reverse the characters of a palindrome, you get the same sequence of characters. Palindromes are commonly used in various contexts, including words (e.g., “radar”, “level”), and numbers (e.g., “12321”, “9009”).
XXIV. Function to Convert Fahrenheit to Celsius:
This code defines a function named fahrenheit_celsius that converts a temperature value from Fahrenheit to Celsius.
def fahrenheit_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
# Call the function
print(fahrenheit_celsius(32))
Here’s how it works:
- Function Definition:
def fahrenheit_celsius(fahrenheit): This function takes a temperature value in Fahrenheit as input.
- Conversion Formula:
- Inside the function, it applies the conversion formula
(fahrenheit - 32) * 5/9to convert the temperature from Fahrenheit to Celsius. - The formula subtracts 32 from the Fahrenheit value to get the temperature difference in Fahrenheit degrees, then multiplies by 5/9 to convert to Celsius.
- Inside the function, it applies the conversion formula
- Calling the Function:
print(fahrenheit_celsius(32)): This line calls thefahrenheit_celsiusfunction with the Fahrenheit temperature value32.- The function computes the equivalent Celsius temperature and prints the result.
- Output:
- The output will be the equivalent Celsius temperature of 32 degrees Fahrenheit, which is
0degrees Celsius.
- The output will be the equivalent Celsius temperature of 32 degrees Fahrenheit, which is
XXV. Function to Calculate Simple Interest:
This code defines a function named simple_interest that calculates the simple interest for a given principal amount, interest rate, and time period.
def simple_interest(principal, rate,time):
return (principal * rate * time) / 100
# Call the function
print(simple_interest(1000,5,2))
Here’s how it works:
- Function Definition:
def simple_interest(principal, rate, time): This function takes three parameters:principal(the initial amount of money),rate(the interest rate per period), andtime(the number of periods).
- Interest Calculation:
- Inside the function, it calculates the simple interest using the formula:
(principal * rate * time) / 100. - It multiplies the principal amount (
principal) by the interest rate (rate) and the time period (time), and then divides the result by 100 to get the simple interest.
- Inside the function, it calculates the simple interest using the formula:
- Calling the Function:
print(simple_interest(1000, 5, 2)): This line calls thesimple_interestfunction with a principal amount of1000, an interest rate of5%, and a time period of2years.- The function computes the simple interest using these parameters and prints the result.
- Output:
- The output will be the calculated simple interest based on the provided principal, interest rate, and time period.
XXVI. Function to Calculate Compound Interest:
This code defines a function named compound_interest that calculates the compound interest for a given principal amount, interest rate, and time period.
def compound_interest(principal, rate, time):
return principal * ((1 + rate / 100) ** time - 1)
# Call the function
print(compound_interest(1000, 5, 2))
Here’s how it works:
- Function Definition:
def compound_interest(principal, rate, time): This function takes three parameters:principal(the initial amount of money),rate(the interest rate per period), andtime(the number of periods).
- Interest Calculation:
- Inside the function, it calculates the compound interest using the formula:
principal * ((1 + rate / 100) ** time - 1). - It first divides the interest rate (
rate) by 100 to convert it to a decimal percentage. - It then calculates the compound interest using the formula for compound interest:
principal * ((1 + rate / 100) ** time - 1).
- Inside the function, it calculates the compound interest using the formula:
- Calling the Function:
print(compound_interest(1000, 5, 2)): This line calls thecompound_interestfunction with a principal amount of1000, an interest rate of5%, and a time period of2years.- The function computes the compound interest using these parameters and prints the result.
- Output:
- The output will be the calculated compound interest based on the provided principal, interest rate, and time period.
XXVII. Function to Reverse a List:
This code defines a function named reverse_list that reverses the order of elements in a given list.
def reverse_list(lst):
return lst[::-1]
# Call the function
print(reverse_list([1,2,3,4,5,6]))
Here’s how it works:
- Function Definition:
def reverse_list(lst): This function takes a listlstas input.
- Reversing the List:
- Inside the function, it returns the input list
lstwith slicing notationlst[::-1]. - This slicing notation creates a reversed copy of the list by starting from the end (
-1) and going backwards to the beginning of the list (::-1).
- Inside the function, it returns the input list
- Calling the Function:
print(reverse_list([1,2,3,4,5,6])): This line calls thereverse_listfunction with the list[1,2,3,4,5,6].- The function reverses the order of elements in the list and prints the result.
- Output:
- The output will be the reversed list, which in this case will be
[6, 5, 4, 3, 2, 1].
- The output will be the reversed list, which in this case will be
XXVIII. Function to Count Occurrences of an Element in a List:
This code defines a function named count_occurrences that counts the number of occurrences of a specific target element in a given list.
def count_occurrences(lst, target):
return lst.count(target)
# Call the function
print(count_occurrences([1,2,2,3,4,2], 2))
Here’s how it works:
- Function Definition:
def count_occurrences(lst, target): This function takes two parameters:lst(the list in which occurrences are counted) andtarget(the element whose occurrences are counted).
- Counting Occurrences:
- Inside the function, it uses the
count()method of lists to count the occurrences of thetargetelement in the listlst. - The
count()method returns the number of occurrences of the specified element in the list.
- Inside the function, it uses the
- Calling the Function:
print(count_occurrences([1,2,2,3,4,2], 2)): This line calls thecount_occurrencesfunction with the list[1,2,2,3,4,2]and the target element2.- The function counts the occurrences of
2in the list and prints the result.
- Output:
- The output will be the number of occurrences of the target element
2in the list[1,2,2,3,4,2], which is3in this case.
- The output will be the number of occurrences of the target element
XXIX. Function to Flatten a Nested List:
This code defines a function named is_leap_year that determines whether a given year is a leap year or not based on the rules of the Gregorian calendar.
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# Call the function
print(is_leap_year(2024))
Here’s how it works:
- Function Definition:
def is_leap_year(year): This function takes a single parameter,year, representing the year to be checked.
- Leap Year Logic:
- The function uses a boolean expression to determine whether the given year is a leap year or not.
- It checks two conditions:
(year % 4 == 0 and year % 100 != 0): This condition checks if the year is divisible by 4 but not by 100. If this condition is true, it indicates a leap year.or (year % 400 == 0): This condition checks if the year is divisible by 400. If true, it overrides the previous condition and also indicates a leap year.
- If either of these conditions is true, the function returns
True, indicating that the year is a leap year. Otherwise, it returnsFalse.
- Calling the Function:
print(is_leap_year(2024)): This line calls theis_leap_yearfunction with the year2024.- The function evaluates whether
2024meets the criteria for a leap year and prints the result.
- Output:
- The output will be
Trueif the given year is a leap year, andFalseotherwise. - In this case,
2024is a leap year, so the output will beTrue.
- The output will be
XXX. Function to Calculate the Fibonacci Series:
This code defines a function named fibonacci that generates a Fibonacci sequence up to the nth term specified by the input parameter n.
def fibonacci(n):
fib_series = [0,1]
while len(fib_series) < n:
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
# Call the function
print(fibonacci(8))
Here’s how it works:
- Function Definition:
def fibonacci(n): This function takes a single parameter,n, representing the number of terms in the Fibonacci sequence to generate.
- Fibonacci Series Initialization:
- Inside the function, a list named
fib_seriesis initialized with the first two terms of the Fibonacci sequence,[0, 1].
- Inside the function, a list named
- Generating Fibonacci Sequence:
- A
whileloop is used to generate additional terms of the Fibonacci sequence until the length offib_seriesreachesn. - Within each iteration of the loop, the next term is calculated by adding the last two terms of the sequence (
fib_series[-1]andfib_series[-2]), and the result is appended tofib_series.
- A
- Returning the Fibonacci Sequence:
- Once the loop completes and the desired number of terms is reached, the function returns the
fib_serieslist containing the Fibonacci sequence up to the nth term.
- Once the loop completes and the desired number of terms is reached, the function returns the
- Calling the Function:
print(fibonacci(8)): This line calls thefibonaccifunction withn = 8, indicating that the Fibonacci sequence up to the 8th term should be generated.- The function calculates the Fibonacci sequence and prints the resulting list.
- Output:
- The output will be the Fibonacci sequence
[0, 1, 1, 2, 3, 5, 8, 13], which consists of eight terms.
- The output will be the Fibonacci sequence