Загрузка...

Types of parameters in python

Python has several types of parameters that you can use in your functions:
1. Positional Parameters:
These are the most basic type of parameters.
They are passed to a function in the order they are defined in the function definition.
Example:
Python

Execution output
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

greet("Alice", 25) # name = "Alice", age = 25
Hello, Alice! You are 25 years old.
2. Keyword Parameters:
These parameters are passed with their names, allowing you to specify the parameter you're assigning a value to.
This makes your code more readable and allows you to pass arguments out of order.
Example:
Python
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

greet(age=30, name="Bob") # name = "Bob", age = 30
3. Default Parameters:
These parameters have a default value assigned to them in the function definition.
If no value is provided for these parameters when calling the function, the default value is used.
Example:
Python
def greet(name, age=18):
print(f"Hello, {name}! You are {age} years old.")

greet("Charlie") # name = "Charlie", age = 18 (default)
4. Variable-Length Positional Parameters (*args):
This allows a function to accept an arbitrary number of positional arguments.
The arguments are packed into a tuple that can be accessed within the function.
Example:
Python
def sum_numbers(*args):
total = 0
for num in args:
total += num
return total

print(sum_numbers(1, 2, 3, 4))

Видео Types of parameters in python канала Coding Bytes
Страницу в закладки Мои закладки
Все заметки Новая заметка Страницу в заметки