Monday, August 25, 2025

🐍ARGUMENTS AND PARAMETERS IN USER DEFINED FUNCTIONS

Functions become powerful when you can pass values to them. Parameters let you design flexible functions, and arguments let you send actual data when calling them.

1) Introduction

In Python, parameters are variables you define in a function, while arguments are the actual values you pass to the function when calling it.


# Defining function with parameter (name)
def greet(name):
    print("Hello,", name)

# Calling function with argument ("Alice")
greet("Alice")   # Output: Hello, Alice

2) Positional Arguments

These must be passed in the correct order. The first argument goes to the first parameter, second to the second, and so on.


def add(a, b):
    print(a + b)

add(5, 3)   # 8
add(10, 20) # 30

Common mistakes:

  • Passing fewer or more arguments → TypeError
  • Wrong order → unexpected results

3) Keyword Arguments

You can specify arguments using name=value. This makes order irrelevant and improves readability.


def introduce(name, age):
    print(f"My name is {name} and I am {age} years old.")

introduce(age=25, name="Alice")  
# Output: My name is Alice and I am 25 years old.

Common mistakes:

  • Positional arguments after keyword arguments → SyntaxError

4) Default Arguments

You can give parameters default values. If no argument is passed, the default is used.


def greet(name="Guest"):
    print("Hello,", name)

greet()          # Output: Hello, Guest
greet("Alice")   # Output: Hello, Alice

Common mistakes:

  • Default parameters must come after non-default ones → otherwise SyntaxError

5) Variable-Length Arguments

Sometimes you don’t know how many arguments a function will get. Python provides:

  • *args → collects extra positional arguments as a tuple
  • **kwargs → collects extra keyword arguments as a dictionary

def total_sum(*numbers):
    print(sum(numbers))

total_sum(1, 2, 3)          # 6
total_sum(5, 10, 15, 20)    # 50

def show_info(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

show_info(name="Alice", age=25, city="London")
# Output:
# name: Alice
# age: 25
# city: London

6) Common Mistakes

  • Forgetting required arguments → TypeError: missing required positional argument
  • Too many arguments → TypeError: takes n positional arguments but m were given
  • Using positional after keyword → SyntaxError
  • Confusing *args and **kwargs

💡 Try It Yourself

  1. Write a function that accepts two numbers and prints their product.
  2. Create a function with default parameter country="Nepal". Call it with and without argument.
  3. Write a function that accepts unlimited numbers using *args and prints the maximum value.
  4. Use **kwargs to print student details (name, grade, age).

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??