Page 1 of 1

Python Functions

Posted: Wed May 29, 2024 12:42 pm
by admin
#Function Basic – (INT21)

Code: Select all

#Creation of Function with variable and Comments
def greet_user(name):
    """A function that greets the user."""
    print(f"Hello, {name}!")

# Calling the function with an argument
greet_user("Ram")
#Function with Operators - (INT22)

Code: Select all

#Creation of Function with Arithmatic Operators
def add_numbers(a, b):
    """A function that returns the sum of two numbers."""
    return a + b

# Calling the function and storing the result
result = add_numbers(3, 7)
print("Sum:", result)
#Functions with default parameters - (INT23)

Code: Select all

#Functions with default parameters 
def power(base, exponent=2):
    """A function with a default parameter value."""
    return base ** exponent

# Calling the function with and without specifying the exponent
result_default = power(3)      # Equivalent to power(3, 2)
result_custom = power(3, 4)

print("Default Exponent:", result_default)  # Result: 9
print("Custom Exponent:", result_custom)    # Result: 81
#Functions with Variable Number of Arguments - (INT24)

Code: Select all

#Functions with Variable Number of Arguments
def sum_all(*numbers):
    """A function with a variable number of arguments."""
    total = sum(numbers)
    return total

# Calling the function with different numbers of arguments
result1 = sum_all(1, 2, 3)
result2 = sum_all(4, 5, 6, 7)

print("Result 1:", result1)  # Result: 6
print("Result 2:", result2)  # Result: 22