FUNCTION BASICS COMMENTED
# 1. Simple Function Definition
def greet(name):
return f"Hello, {name}!" # Returns a greeting string with
the given name
# Usage
user_name = input("Enter your name: ") # Get user input for
the name
print(greet(user_name)) # Call the function and print the
result
# 2. Function with Multiple Parameters
def add_numbers(a, b):
return a + b # Returns the sum of two numbers
# Usage
num1 = int(input("Enter first number: ")) # Get first number
from user
num2 = int(input("Enter second number: ")) # Get second
number from user
print(f"Sum: {add_numbers(num1, num2)}") # Call the function
and print the result
# 3. Function with Default Parameters
def power(base, exponent=2): # exponent has a default value
of 2
return base ** exponent # Returns base raised to the
power of exponent
# Usage
base = int(input("Enter base number: ")) # Get base number
from user
exp = input("Enter exponent (press Enter for default): ") #
Get exponent or use default
if exp:
print(f"Result: {power(base, int(exp))}") # Call with
custom exponent
else:
print(f"Result: {power(base)}") # Call with default
exponent
# 4. Function with Variable Number of Arguments
def sum_all(*args): # *args allows any number of arguments
return sum(args) # Returns the sum of all arguments
# Usage
numbers = [int(x) for x in input("Enter numbers separated by
space: ").split()] # Get multiple numbers from user
print(f"Sum of all numbers: {sum_all(*numbers)}") # Call the
function with unpacked list
print(f"Sum of all numbers: {sum_all(*numbers)}") # Call the
function with unpacked list
# 5. Function with Keyword Arguments
def person_info(**kwargs): # **kwargs allows any number of
keyword arguments
for key, value in kwargs.items():
print(f"{key}: {value}") # Prints each key-value pair
# Usage
name = input("Enter name: ") # Get name from user
age = int(input("Enter age: ")) # Get age from user
city = input("Enter city: ") # Get city from user
person_info(name=name, age=age, city=city) # Call function
with keyword arguments
# 6. Function as Return Value
def make_multiplier(n):
def multiplier(x):
return x * n # Returns a function that multiplies by
n
return multiplier
# Usage
factor = int(input("Enter a factor: ")) # Get factor from
user
multiply_by_factor = make_multiplier(factor) # Create a new
function
number = int(input("Enter a number to multiply: ")) # Get
number to multiply
print(f"Result: {multiply_by_factor(number)}") # Call the new
function
# 7. Recursive Function
def factorial(n):
if n == 0 or n == 1:
return 1 # Base case
else:
return n * factorial(n-1) # Recursive case
# Usage
num = int(input("Enter a number to calculate factorial: ")) #
Get number from user
print(f"Factorial: {factorial(num)}") # Call the recursive
function
# 8. Lambda Function
square = lambda x: x**2 # One-line function to square a
number
# Usage
num = int(input("Enter a number to square: ")) # Get number
from user
print(f"Square: {square(num)}") # Call the lambda function
# 9. Higher-Order Function
def apply_operation(func, x, y):
return func(x, y) # Applies the given function to x and y
# Usage
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second
number
operation = input("Enter operation (add/multiply): ") # Get
operation choice
if operation == "add":
result = apply_operation(lambda a, b: a + b, num1, num2)
# Use lambda for addition
elif operation == "multiply":
result = apply_operation(lambda a, b: a * b, num1, num2)
# Use lambda for multiplication
else:
result = "Invalid operation"
print(f"Result: {result}") # Print the result of the
operation
# 10. Function with Type Hints
def calculate_area(length: float, width: float) -> float:
return length * width # Returns the area of a rectangle
# Usage
length = float(input("Enter length: ")) # Get length from
user
width = float(input("Enter width: ")) # Get width from user
print(f"Area: {calculate_area(length, width)}") # Call the
function with type hints
# 11. Generator Function
def countdown(n):
while n > 0:
yield n # Yields the next value in the sequence
n -= 1
# Usage
start = int(input("Enter start number for countdown: ")) #
Get start number
for num in countdown(start): # Iterate over the generator
print(num, end=' ')
print("Blast off!")
# 12. Decorator Function
def uppercase_decorator(func):
def wrapper():
result = func()
return result.upper() # Converts the result to
uppercase
return wrapper
@uppercase_decorator # Apply the decorator to the function
def greet():
return input("Enter a greeting: ") # Get greeting from
user
# Usage
print(greet()) # Call the decorated function
# 13. Function with Error Handling
def divide(a, b):
try:
return a / b # Attempt to divide a by b
except ZeroDivisionError:
return "Error: Division by zero" # Handle division by
zero
# Usage
num1 = float(input("Enter numerator: ")) # Get numerator
num2 = float(input("Enter denominator: ")) # Get denominator
print(f"Result: {divide(num1, num2)}") # Call the function
with error handling
# 14. Function with Local and Global Variables
global_var = 10 # Define a global variable
def modify_global():
global global_var # Declare the variable as global
local_var = 20 # Define a local variable
global_var += local_var # Modify the global variable
return global_var
# Usage
print(f"Before modification: {global_var}") # Print global
variable before
print(f"After modification: {modify_global()}") # Call
function and print result
# 15. Closure
def outer_function(x):
def inner_function(y):
return x + y # Inner function has access to x
return inner_function # Return the inner function
# Usage
outer = outer_function(int(input("Enter outer number: "))) #
Create closure
result = outer(int(input("Enter inner number: "))) # Use the
closure
print(f"Result: {result}") # Print the result