Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → parameters

Python Functions

parameters

In Python, functions are reusable blocks of code that perform specific tasks. Parameters (also called arguments) are the input values you provide to a function when you call it. They act as placeholders that receive data, allowing the function to operate on different inputs without needing to be rewritten. Understanding how parameters work is crucial for writing flexible and efficient Python code. Types of Parameters: Python offers several ways to define and use parameters, adding flexibility to how you handle function inputs. Let's explore them:

Positional Parameters

These are the most basic type of parameters. Their position in the function definition determines the order in which you must provide arguments when calling the function.
Positional Parameters in python function def greet(name, greeting): # name and greeting are positional parameters print(f"{greeting}, {name}!") greet("Alice", "Hello") greet("Bob", "Good morning") # Incorrect order leads to error: # greet("Hello", "Alice")

Output

Hello, Alice! Good morning, Bob!

Keyword Arguments

Keyword arguments specify the parameter name along with the value. This makes the code more readable and allows you to pass arguments in any order.
Keyword Arguments in python function def describe_pet(animal_type, pet_name, age=None): # age is an optional keyword argument with a default value print(f"\ I have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}.") if age: print(f"My {animal_type} is {age} years old.") describe_pet(animal_type='hamster', pet_name='harry') # Order doesn't matter describe_pet(pet_name='willie', animal_type='dog', age=3) # Different order, still works

Output

I have a hamster. My hamster's name is Harry. I have a dog. My dog's name is Willie. My dog is 3 years old.

Default Arguments

Default arguments provide a default value for a parameter if no value is explicitly passed when calling the function. This makes functions more versatile.
Default Arguments in python function def make_pizza(size, toppings='pepperoni'): # toppings has a default value print(f"Making a {size}-inch pizza with {toppings}.") make_pizza(12) # Uses the default topping ('pepperoni') make_pizza(16, 'mushrooms') # Overrides the default topping

Output

Making a 12-inch pizza with pepperoni. Making a 16-inch pizza with mushrooms.

Variable-length Arguments (*args and **kwargs)

These parameters allow you to pass a variable number of arguments to a function. ✦ `*args`: Collects any number of positional arguments into a tuple.
Collects any number of positional arguments into a tuple def sum_all(*numbers): total = 0 for number in numbers: total += number return total print(sum_all(1, 2, 3)) print(sum_all(10, 20, 30, 40, 50))

Output

6 150

✦ `**kwargs`: Collects any number of keyword arguments into a dictionary.
Collects any number of keyword arguments into a dictionary def print_details(**details): for key, value in details.items(): print(f"{key}: {value}") print_details(name="Alice", age=30, city="New York")

Output

name: Alice age: 30 city: New York

Combining Parameter Types

You can combine different parameter types in a single function definition, but positional parameters must come before keyword parameters, and parameters with default values must come after those without defaults.
Combining Parameter Types in python function def complex_function(pos1, pos2, key1='default', *args, **kwargs): print("Positional:", pos1, pos2) print("Keyword:", key1) print("Variable Positional:", args) print("Variable Keyword:", kwargs) complex_function(1, 2, key1='override', extra1='a', extra2='b')

Output

Positional: 1 2 Keyword: override Variable Positional: () Variable Keyword: {'extra1': 'a', 'extra2': 'b'}

Parameter Passing in Python (Call by Object Reference)

Python uses a mechanism often described as "call by object reference". When you pass an immutable object (like an integer or string) to a function, a copy of its value is created. Changes within the function don't affect the original object. However, when you pass a mutable object (like a list or dictionary), the function receives a reference to the original object. Modifying the object inside the function *will* change the original object.
Parameter Passing in Python (Call by Object Reference) python example def modify_list(my_list): my_list.append(4) my_list = [1, 2, 3] modify_list(my_list) print(my_list) def modify_number(x): x += 1 num = 5 modify_number(num) print(num)

Output

[1, 2, 3, 4] 5

Understanding these aspects of Python function parameters is crucial for writing well-structured, readable, and reusable code. Using the appropriate parameter types allows you to create flexible and powerful functions that adapt to various input scenarios.

Tutorials