Python Basic Functions with Explanation
1. Function to Add Two Numbers
def add_numbers(a, b):
return a + b
# Example
result = add_numbers(5, 3)
print(result)
Explanation: This function takes two numbers as input and returns their sum.
2. Function to Check Even or Odd
def is_even(number):
if number % 2 == 0:
return True
return False
# Example
print(is_even(10))
print(is_even(7))
Explanation: This function checks if a given number is even or odd by using the modulo operator.
3. Function to Find Factorial
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
# Example
print(factorial(5))
Explanation: This recursive function calculates the factorial of a given number.
4. Function to Reverse a String
def reverse_string(s):
return s[::-1]
# Example
print(reverse_string('hello'))
Explanation: This function reverses the input string using Python slicing.
5. Function to Find Maximum in a List
def find_max(lst):
return max(lst)
# Example
print(find_max([1, 2, 3, 4, 5]))
Explanation: This function returns the maximum value in a list using Python's built-in max() function.