StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Passing parameters
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
Function Invoking : Scope of variables
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

Passing parameters is the process of giving data (arguments) to a function when you call it. The function then uses this data, via its parameters, to perform its task. Python offers several flexible and powerful ways to pass arguments to functions.

1. Positional Arguments

This is the most common and straightforward way to pass arguments. The values you pass are matched to the parameters in the function definition based on their order, or position.

  • Use Case: For functions with a small, fixed number of required parameters where the order is logical and easy to remember (e.g., calculate_area(length, width)).

Python

# --- Positional Arguments Example ---

 

# 'name' and 'age' are parameters that expect positional arguments.

def display_user_info(name, age):

    print(f"Name: {name}, Age: {age}")

 

# The first argument "Rohit" is passed to 'name'.

# The second argument 30 is passed to 'age'.

display_user_info("Rohit", 30)


2. Keyword Arguments

You can explicitly name which parameter each argument should be assigned to. When you use keyword arguments, the order no longer matters.

  • Use Case: For functions with many parameters, especially optional ones, to improve code readability and avoid mistakes with the order.

Python

# --- Keyword Arguments Example ---

 

def create_email(recipient, subject, body):

    print(f"To: {recipient}")

    print(f"Subject: {subject}")

    print(f"Body: {body}")

 

# The order of arguments is different from the parameter order,

# but the code works correctly because the names are specified.

create_email(

    subject="Project Update",

    body="Here is the latest update on the project.",

    recipient="Neha@example.com"

)


3. Default Parameter Values

You can assign a default value to a parameter in the function definition. This makes the argument for that parameter optional. If the caller doesn't provide a value for it, the default value is used.

  • Use Case: For settings or options that have a common, standard value but can be overridden when needed (e.g., a timeout parameter that defaults to 30 seconds).

Python

# --- Default Parameter Values Example ---

 

# 'role' has a default value of "user".

def create_user(username, role="user"):

    print(f"Creating user '{username}' with role '{role}'.")

 

# Call the function without providing the 'role' argument.

create_user("Rohit")

 

# Call the function and override the default value.

create_user("Neha", role="admin")


4. Arbitrary Positional Arguments (*args)

Sometimes you don't know in advance how many positional arguments a function will receive. By placing an asterisk * before a parameter name (conventionally *args), you can tell the function to accept any number of positional arguments. These arguments are then collected into a tuple.

  • Use Case: For functions that need to perform an operation on a variable number of inputs, such as calculating the sum or average of a group of numbers.

Python

# --- Arbitrary Positional Arguments (*args) Example ---

 

# This function can accept any number of numeric arguments.

def sum_all(*args):

    total = 0

    for number in args: # 'args' is a tuple containing all passed arguments

        total += number

    return total

 

# Call the function with different numbers of arguments.

print(f"Sum of 1, 2, 3: {sum_all(1, 2, 3)}")

print(f"Sum of 10, 20, 30, 40, 50: {sum_all(10, 20, 30, 40, 50)}")


5. Arbitrary Keyword Arguments (**kwargs)

Similarly, you might want a function to accept any number of keyword arguments. By placing two asterisks ** before a parameter name (conventionally **kwargs), you can tell the function to accept any number of keyword arguments. These arguments are then collected into a dictionary.

  • Use Case: For functions that need to handle flexible or optional attributes, such as processing user profile data where some fields might be missing.

Python

# --- Arbitrary Keyword Arguments (**kwargs) Example ---

 

# This function can accept any number of keyword arguments.

def display_profile(**kwargs):

    print("User Profile:")

    # 'kwargs' is a dictionary containing all passed keyword arguments.

    for key, value in kwargs.items():

        print(f"- {key.capitalize()}: {value}")

 

# Call the function with different keyword arguments.

display_profile(name="Neha", age=30, city="Mumbai")

print("-" * 20)

display_profile(name="Rohit", occupation="Engineer")

 

Function Invoking Scope of variables
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website