Hello World Function
def say_hello():
print("Hello, World!")
# Call the function
say_hello()
2. Function with Parameters
def greet(name):
print(f"Hello, {name}!")
# Call the function
greet("Alice")
3. Function with Return Value
def add(a, b):
return a + b
# Call the function and store the result
result = add(3, 5)
print("Sum:", result)
4. Function with Default Parameter
def greet_with_default(name="Guest"):
print(f"Welcome, {name}!")
# Call the function
greet_with_default() # Uses default value
greet_with_default("John") # Uses given value
5. Function with Multiple Return Values
def divide_and_remainder(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
# Call the function
q, r = divide_and_remainder(10, 3)
print(f"Quotient: {q}, Remainder: {r}")
6. Function with Variable-Length Arguments
def print_numbers(*numbers):
for number in numbers:
print(number)
# Call the function with different numbers of arguments
print_numbers(1, 2, 3)
print_numbers(5, 10, 15, 20)
7. Lambda Function (Anonymous Function)
# Lambda to calculate the square of a number
square = lambda x: x * x
# Use the lambda function
print("Square of 4:", square(4))
8. Recursive Function
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Call the function
print("Factorial of 5:", factorial(5))
9. Function with Keyword Arguments
def describe_pet(name, animal_type="dog"):
print(f"{name} is a {animal_type}.")
# Call the function
describe_pet("Buddy")
describe_pet("Whiskers", animal_type="cat")
10. Function with Docstring
def add(a, b):
"""
This function adds two numbers.
Parameters:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of a and b.
"""
return a + b
# Call the function
print("Sum:", add(10, 20))