Mastering Python Functions: Arguments, Scope, and Returns
Keyword Arguments
Arguments are passed using parameter names, meaning the order does not matter.
Example
def func(name, age):
return f"Hello {name}, you are {age} years old!"
result = func(age=18, name="John")
print(result)Output: Hello John, you are 18 years old!
Default Arguments
Default values are assigned to parameters directly in the function definition.
Example
def func(name, greeting="Hello"):
return f"{greeting}, {name}"
print(func("John"))
print(func("Nik", "Hi"))Output:
Hello, John
Hi, Nik
Arbitrary Arguments
Used when the number of arguments passed to a function is unknown.
*args – Non-keyword variable length arguments
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 5, 10, 15))Output: 31
**kwargs – Keyword variable length arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="John", age=18, city="Jammu")Output:
name: John
age: 18
city: Jammu
Local Scope vs. Global Scope
| Aspect | Local Variable | Global Variable |
|---|---|---|
| Definition | Declared inside a function | Declared outside a function |
| Accessibility | Accessible only inside the function | Accessible anywhere in the program |
| Lifetime | Exists only during function execution | Exists for the entire program |
| Modification | Modified inside the function | Can be modified using global keyword |
Example
x = 20 # Global variable
def example_function():
print(x)
example_function()
print(x)Output:
20
20
Return Statement in Python
A return statement is used to send a value from a function back to the caller.
Syntax
def function_name(parameters):
return valueExample
def add_numbers(a, b):
return a + b
sum_value = add_numbers(2, 9)
print("The sum is:", sum_value)Output: The sum is: 11
Explanation
- The function takes two numbers as parameters.
- It calculates the sum.
- The result is returned to the calling statement.
- The returned value is then printed.
English with a size of 2.65 KB