Mastering Python Functions: Arguments, Scope, and Returns

Posted by Anonymous and classified in Computers

Written on in English with a size of 2.65 KB

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

AspectLocal VariableGlobal Variable
DefinitionDeclared inside a functionDeclared outside a function
AccessibilityAccessible only inside the functionAccessible anywhere in the program
LifetimeExists only during function executionExists for the entire program
ModificationModified inside the functionCan 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 value

Example

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.

Related entries: