Meritshot Tutorials

  1. Home
  2. »
  3. Parameters and Arguments in Python

Python Tutorial

Parameters and Arguments

1.1 Parameters

Parameters are like variables inside a function. They let the function know what information it will work with.

def multiply(a, b):

return a * b

  • a and b are parameters

result = multiply(4, 5)

print(result)

20

4 and 5 are arguments

1.2 Types of Arguments

1.   Positional Arguments:

The order of arguments matters.

def subtract(a, b):

return a – b

print(subtract(10, 5))

2.   Keyword Arguments:

You specify which value goes to which parameter.

def divide(a, b):

return a / b

print(divide(a=10, b=2))

5.0

3. Default Arguments: Provide default values if no argument is given

def greet(name=”Mehmaan”): print(f”Namaste, {name}!”)

greet() greet(“Succhi”)

Namaste,  Mehmaan!

Namaste, Succhi!

4. Variable-Length Arguments: Allow for a variable number of

def print_info(*args, **kwargs): print(“Arguments:”, args)

print(“Keyword Arguments:”, kwargs)

print_info(1, 2, 3, a=4, b=5)

Arguments: (1, 2, 3)

Keyword Arguments: {‘a’: 4, ‘b’: 5}

The function print_info(*args, **kwargs) can take any number of positional arguments (*args) and keyword arguments (**kwargs). When you call print_info(1, 2, 3, a=4, b=5), the positional arguments (1, 2, 3) are stored in a tuple called args, and the keyword arguments (a=4, b=5) are stored in a dictionary called kwargs. The function then prints both of these.

5. Python Global Keyword: allows to modify a global variable inside a function.

What is global Variable ? A global variable in Python is like a value or piece of information that you can use anywhere in your code. It’s created outside of any specific function, so any function in your program can use or change it.

# This is a global variable

message = “Awwie”

def print_message():

# Using the global variable

print(message)

 

print_message()

Awwie

Using python global keyword

counter = 0

def increase_counter(): global counter counter += 1

increase_counter()

 print(counter)

1

The global counter line tells Python that we’re referring to the global counter variable, not creating a new local one.

As you can see counter = 0 is the global varibale which can’t be changed inside any function but by using global keyword we are able to change the value of global variable

1.2 Types of Arguments

  • You can use the global keyword to declare that a variable inside a function is
  • Without global, any assignment to a variable inside a function makes it a local
  • The global keyword is not needed to read global variables, only to modify