Types of Functions Based on Arguments

Types of Functions Based on Arguments

Table of Contents

Program 1: Simple Addition of Two Numbers

Program:

def add(a, b):
    """Add two numbers using positional arguments."""
    return a + b

# Test the function
print("Sum of 5 and 7:", add(5, 7))

Expected Output:

Sum of 5 and 7: 12

Program 2: Calculate the Difference Between Two Numbers

Program:

def subtract(a, b):
    """Subtract the second number from the first using positional arguments."""
    return a - b

# Test the function
print("Difference between 10 and 3:", subtract(10, 3))

Expected Output:

Difference between 10 and 3: 7

Program 3: Multiply Two Numbers

Program:

def multiply(a, b):
    """Multiply two numbers using positional arguments."""
    return a * b

# Test the function
print("Product of 4 and 6:", multiply(4, 6))

Expected Output:

Product of 4 and 6: 24

Program 4: Divide Two Numbers

Program:

def divide(a, b):
    """Divide the first number by the second using positional arguments."""
    if b != 0:
        return a / b
    else:
        return "Error: Division by zero"

# Test the function
print("Division of 20 by 4:", divide(20, 4))

Expected Output:

Division of 20 by 4: 5.0

Program 5: Calculate Power of a Number

Program:

def power(base, exponent):
    """Calculate the power of a number using positional arguments."""
    return base ** exponent

# Test the function
print("2 raised to the power of 3:", power(2, 3))

Expected Output:

2 raised to the power of 3: 8

Program 6: Swap Two Numbers

Program:

def swap(a, b):
    """Swap two numbers using positional arguments."""
    return b, a

# Test the function
x, y = swap(10, 20)
print("After swapping: x =", x, ", y =", y)

Expected Output:

After swapping: x = 20 , y = 10

Program 7: Calculate Average of Two Numbers

Program:

def average(a, b):
    """Calculate the average of two numbers using positional arguments."""
    return (a + b) / 2

# Test the function
print("Average of 5 and 9:", average(5, 9))

Expected Output:

Average of 5 and 9: 7.0

Program 8: Check if Two Numbers Are Equal

Program:

def are_equal(a, b):
    """Check if two numbers are equal using positional arguments."""
    return a == b

# Test the function
print("Are 10 and 10 equal?", are_equal(10, 10))

Expected Output:

Are 10 and 10 equal? True

Program 9: Find Maximum of Two Numbers

Program:

def maximum(a, b):
    """Return the maximum of two numbers using positional arguments."""
    return max(a, b)

# Test the function
print("Maximum of 15 and 20:", maximum(15, 20))

Expected Output:

Maximum of 15 and 20: 20

Program 10: Find Minimum of Two Numbers

Program:

def minimum(a, b):
    """Return the minimum of two numbers using positional arguments."""
    return min(a, b)

# Test the function
print("Minimum of 30 and 25:", minimum(30, 25))

Expected Output:

Minimum of 30 and 25: 25

Default Arguments (10 Programs)


Program 1: Greet with Default Name

Program:

def greet(name="User"):
    """Greet a person, with a default name if none is provided."""
    return f"Hello, {name}!"

# Test the function
print(greet())           # Using default argument
print(greet("Alice"))    # Using custom argument

Expected Output:

Hello, User!
Hello, Alice!

Program 2: Calculate the Price After Discount (with Default Discount)

Program:

def calculate_price(original_price, discount=10):
    """Calculate price after applying a discount. Default discount is 10%."""
    discounted_price = original_price * (1 - discount / 100)
    return discounted_price

# Test the function
print("Price after discount (default 10%):", calculate_price(100))
print("Price after discount (20%):", calculate_price(100, 20))

Expected Output:

Price after discount (default 10%): 90.0
Price after discount (20%): 80.0

Program 3: Get Discounted Price with Default Tax

Program:

def calculate_total_price(price, discount=5, tax=8):
    """Calculate total price after discount and tax (default tax is 8%)."""
    discounted_price = price - (price * discount / 100)
    total_price = discounted_price + (discounted_price * tax / 100)
    return total_price

# Test the function
print("Total price with default discount and tax:", calculate_total_price(200))
print("Total price with custom discount and tax:", calculate_total_price(200, 10, 12))

Expected Output:

Total price with default discount and tax: 199.04
Total price with custom discount and tax: 198.0

Program 4: Calculate Rectangle Area with Default Width

Program:

def calculate_area(length, width=5):
    """Calculate area of a rectangle, with default width 5."""
    return length * width

# Test the function
print("Area with default width:", calculate_area(10))
print("Area with custom width:", calculate_area(10, 8))

Expected Output:

Area with default width: 50
Area with custom width: 80

Program 5: Display Full Name (with Default Middle Name)

Program:

def display_name(first_name, last_name, middle_name=""):
    """Display full name, with an optional middle name."""
    if middle_name:
        return f"{first_name} {middle_name} {last_name}"
    else:
        return f"{first_name} {last_name}"

# Test the function
print(display_name("John", "Doe"))          # Without middle name
print(display_name("John", "Doe", "Michael")) # With middle name

Expected Output:

John Doe
John Michael Doe

Program 6: Find the Total Price (with Default Tax)

Program:

def find_total_price(price, tax_rate=5):
    """Find total price including tax. Default tax rate is 5%."""
    total_price = price + (price * tax_rate / 100)
    return total_price

# Test the function
print("Total price (default 5% tax):", find_total_price(200))
print("Total price (10% tax):", find_total_price(200, 10))

Expected Output:

Total price (default 5% tax): 210.0
Total price (10% tax): 220.0

Program 7: Calculate Circle Circumference (with Default Pi)

Program:

def calculate_circumference(radius, pi=3.14159):
    """Calculate the circumference of a circle, with default value of pi."""
    return 2 * pi * radius

# Test the function
print("Circumference (default pi):", calculate_circumference(7))
print("Circumference (custom pi):", calculate_circumference(7, 3.14))

Expected Output:

Circumference (default pi): 43.98226
Circumference (custom pi): 43.96

Program 8: Calculate Compound Interest (with Default Rate)

Program:

def compound_interest(principal, rate=5, time=1):
    """Calculate compound interest with default rate 5% and time 1 year."""
    amount = principal * (1 + rate / 100) ** time
    return amount - principal

# Test the function
print("Compound interest (default rate and time):", compound_interest(1000))
print("Compound interest (custom rate and time):", compound_interest(1000, 7, 2))

Expected Output:

Compound interest (default rate and time): 50.0
Compound interest (custom rate and time): 140.0

Program 9: Get Greeting Message (with Default Language)

Program:

def greet(language="English"):
    """Return a greeting message in the specified language."""
    greetings = {
        "English": "Hello!",
        "Spanish": "¡Hola!",
        "French": "Bonjour!",
        "German": "Hallo!"
    }
    return greetings.get(language, "Hello!")

# Test the function
print(greet())          # Default English
print(greet("Spanish")) # Custom Spanish

Expected Output:

Hello!
¡Hola!

Program 10: Calculate Perimeter of a Square (with Default Side Length)

Program:

def calculate_perimeter(side_length=4):
    """Calculate the perimeter of a square, with default side length 4."""
    return 4 * side_length

# Test the function
print("Perimeter of square (default side length):", calculate_perimeter())
print("Perimeter of square (side length 6):", calculate_perimeter(6))

Expected Output:

Perimeter of square (default side length): 16
Perimeter of square (side length 6): 24

Let’s continue with the next category: Keyword Arguments. You requested 10 programs for this type of function argument. Here are the programs focusing on Keyword Arguments.

See also  Exception Handling in Python

Keyword Arguments (10 Programs)


Program 1: Greeting with Custom Message

Program:

def greet(message, name="User"):
    """Greet with a custom message using keyword arguments."""
    return f"{message}, {name}!"

# Test the function
print(greet("Hello"))           # Default name
print(greet("Good Morning", "Alice"))  # Custom name

Expected Output:

Hello, User!
Good Morning, Alice!

Program 2: Calculate Total Price with Custom Tax Rate

Program:

def calculate_price(price, discount=10, tax_rate=8):
    """Calculate total price with discount and tax using keyword arguments."""
    price_after_discount = price - (price * discount / 100)
    total_price = price_after_discount + (price_after_discount * tax_rate / 100)
    return total_price

# Test the function
print("Total price (default discount and tax):", calculate_price(100))
print("Total price (custom discount and tax):", calculate_price(100, discount=15, tax_rate=12))

Expected Output:

Total price (default discount and tax): 90.0
Total price (custom discount and tax): 85.5

Program 3: Display Full Name with Optional Middle Name

Program:

def display_full_name(first_name, last_name, middle_name=""):
    """Display full name using keyword arguments."""
    if middle_name:
        return f"{first_name} {middle_name} {last_name}"
    return f"{first_name} {last_name}"

# Test the function
print(display_full_name("John", "Doe"))              # Without middle name
print(display_full_name("John", "Doe", middle_name="Michael"))  # With middle name

Expected Output:

John Doe
John Michael Doe

Program 4: Set Personal Details with Default Age

Program:

def set_personal_details(name, age=25, city="Unknown"):
    """Set personal details using keyword arguments."""
    return f"Name: {name}, Age: {age}, City: {city}"

# Test the function
print(set_personal_details("Alice"))                       # Using default age and city
print(set_personal_details("Bob", age=30, city="New York")) # Custom age and city

Expected Output:

Name: Alice, Age: 25, City: Unknown
Name: Bob, Age: 30, City: New York

Program 5: Create an Account with Default Country

Program:

def create_account(username, password, country="USA"):
    """Create an account with default country using keyword arguments."""
    return f"Account created for {username} in {country}"

# Test the function
print(create_account("john_doe", "secure123"))             # Using default country
print(create_account("jane_doe", "password456", country="Canada"))  # Custom country

Expected Output:

Account created for john_doe in USA
Account created for jane_doe in Canada

Program 6: Calculate Salary with Bonus and Tax Rate

Program:

def calculate_salary(base_salary, bonus=500, tax_rate=10):
    """Calculate salary after bonus and tax using keyword arguments."""
    salary_after_bonus = base_salary + bonus
    salary_after_tax = salary_after_bonus - (salary_after_bonus * tax_rate / 100)
    return salary_after_tax

# Test the function
print("Salary after bonus and tax:", calculate_salary(3000))  # Using default bonus and tax
print("Salary with custom bonus and tax:", calculate_salary(3000, bonus=1000, tax_rate=15))  # Custom bonus and tax

Expected Output:

Salary after bonus and tax: 3150.0
Salary with custom bonus and tax: 3650.0

Program 7: Calculate Rectangle Area with Keyword Arguments

Program:

def calculate_area(length, width):
    """Calculate area of a rectangle using keyword arguments."""
    return length * width

# Test the function
print("Area of rectangle:", calculate_area(length=5, width=3))

Expected Output:

Area of rectangle: 15

Program 8: Set Contact Information with Optional Email

Program:

def set_contact_info(phone, email=None):
    """Set contact information with optional email."""
    if email:
        return f"Phone: {phone}, Email: {email}"
    return f"Phone: {phone}, Email: Not provided"

# Test the function
print(set_contact_info("1234567890"))                  # Without email
print(set_contact_info("1234567890", email="alice@example.com")) # With email

Expected Output:

Phone: 1234567890, Email: Not provided
Phone: 1234567890, Email: alice@example.com

Program 9: Calculate Final Score with Default Grading

Program:

def calculate_score(total_marks, obtained_marks, grading="Standard"):
    """Calculate final score based on grading method."""
    score = (obtained_marks / total_marks) * 100
    return f"Final score ({grading}): {score}%"

# Test the function
print(calculate_score(100, 85))  # Using default grading
print(calculate_score(100, 85, grading="Premium"))  # Custom grading

Expected Output:

Final score (Standard): 85.0%
Final score (Premium): 85.0%

Program 10: Print Custom Message with Default Greeting

Program:

def print_message(message, greeting="Hello"):
    """Print a custom message with a default greeting."""
    return f"{greeting}, {message}"

# Test the function
print(print_message("Welcome to the Python world!"))  # Default greeting
print(print_message("Welcome to the Python world!", greeting="Hi"))  # Custom greeting

Expected Output:

Hello, Welcome to the Python world!
Hi, Welcome to the Python world!

Variable Length Arguments (10 Programs)


Program 1: Calculate the Sum of Any Number of Arguments

Program:

def calculate_sum(*args):
    """Calculate the sum of any number of arguments."""
    return sum(args)

# Test the function
print("Sum of numbers:", calculate_sum(1, 2, 3, 4))  # 1 + 2 + 3 + 4
print("Sum of numbers:", calculate_sum(10, 20, 30))  # 10 + 20 + 30

Expected Output:

Sum of numbers: 10
Sum of numbers: 60

Program 2: Concatenate Multiple Strings

Program:

def concatenate_strings(*args):
    """Concatenate multiple strings together."""
    return " ".join(args)

# Test the function
print("Concatenated string:", concatenate_strings("Hello", "world", "from", "Python"))
print("Concatenated string:", concatenate_strings("I", "love", "programming"))

Expected Output:

Concatenated string: Hello world from Python
Concatenated string: I love programming

Program 3: Calculate the Average of Multiple Numbers

Program:

def calculate_average(*args):
    """Calculate the average of multiple numbers."""
    return sum(args) / len(args)

# Test the function
print("Average:", calculate_average(10, 20, 30, 40))  # (10 + 20 + 30 + 40) / 4
print("Average:", calculate_average(5, 15, 25))

Expected Output:

Average: 25.0
Average: 15.0

Program 4: Find the Maximum Value Among Multiple Numbers

Program:

def find_maximum(*args):
    """Find the maximum value among multiple numbers."""
    return max(args)

# Test the function
print("Maximum value:", find_maximum(10, 20, 30, 40))
print("Maximum value:", find_maximum(100, 200, 50))

Expected Output:

Maximum value: 40
Maximum value: 200

Program 5: Multiply Any Number of Arguments

Program:

def multiply_numbers(*args):
    """Multiply any number of arguments together."""
    result = 1
    for num in args:
        result *= num
    return result

# Test the function
print("Product of numbers:", multiply_numbers(2, 3, 4))  # 2 * 3 * 4
print("Product of numbers:", multiply_numbers(5, 6))

Expected Output:

Product of numbers: 24
Product of numbers: 30

Program 6: Join Multiple Lists Together

Program:

def join_lists(*args):
    """Join multiple lists together into one."""
    result = []
    for lst in args:
        result.extend(lst)
    return result

# Test the function
print("Joined list:", join_lists([1, 2], [3, 4], [5, 6]))
print("Joined list:", join_lists([1, 2], [7, 8]))

Expected Output:

Joined list: [1, 2, 3, 4, 5, 6]
Joined list: [1, 2, 7, 8]

Program 7: Print Multiple Messages

Program:

def print_messages(*args):
    """Print multiple messages."""
    for message in args:
        print(message)

# Test the function
print_messages("Hello!", "How are you?", "Goodbye!")

Expected Output:

Hello!
How are you?
Goodbye!

Program 8: Find the Length of Multiple Strings

Program:

def find_lengths(*args):
    """Find the length of each string in the arguments."""
    return [len(arg) for arg in args]

# Test the function
print("Lengths of strings:", find_lengths("apple", "banana", "cherry"))
print("Lengths of strings:", find_lengths("python", "programming"))

Expected Output:

Lengths of strings: [5, 6, 6]
Lengths of strings: [6, 11]

Program 9: Combine Multiple Dictionaries

Program:

def combine_dicts(*args):
    """Combine multiple dictionaries into one."""
    result = {}
    for dictionary in args:
        result.update(dictionary)
    return result

# Test the function
print("Combined dictionary:", combine_dicts({"a": 1}, {"b": 2}, {"c": 3}))
print("Combined dictionary:", combine_dicts({"name": "Alice"}, {"age": 25}, {"city": "New York"}))

Expected Output:

Combined dictionary: {'a': 1, 'b': 2, 'c': 3}
Combined dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Program 10: Print Key-Value Pairs from Multiple Dictionaries

Program:

def print_key_value_pairs(*args):
    """Print key-value pairs from multiple dictionaries."""
    for dictionary in args:
        for key, value in dictionary.items():
            print(f"{key}: {value}")

# Test the function
print_key_value_pairs({"name": "Alice"}, {"age": 25}, {"city": "New York"})

Expected Output:

name: Alice
age: 25
city: New York

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Contact Form Demo