DEV Community

Cover image for 🎁Learn Python in 10 Days: Day6
William
William

Posted on

🎁Learn Python in 10 Days: Day6

Today, we're continuing our 10-day journey to learn Python, kicking off Day 6's lesson. If you haven't checked out Day 1 yet, you can find it here: 🎁Learn Python in 10 Days: Day 1

Day 6: Advanced Functions 🎉

1. Multiple Return Values in Functions

If a function has multiple return values, only the first return statement will be executed. This is because the return statement exits the current function, causing any code beneath it to not be executed.

def return_num():
    return 1
    return 2
result = return_num()
print(result)
Enter fullscreen mode Exit fullscreen mode

To have a function return multiple values, simply list the variables that will capture the return values separated by commas. This supports different types of data being returned.

def return_num():
    return 1, 2
result1, result2 = return_num()
print(result1)
print(result2)
Enter fullscreen mode Exit fullscreen mode

2. Different Ways to Pass Arguments to Functions

Depending on usage, there are four common ways to pass arguments to functions:

  • Positional arguments
  • Keyword arguments
  • Variable-length arguments
  • Default arguments

2.1 Positional Arguments

This refers to passing arguments to the function based on the position of parameters defined in the function.

def user_info(name, age, gender):
    print(f"Your name is: {name}, age is {age}, gender is {gender}")
user_info("Alex", 25, "male")
Enter fullscreen mode Exit fullscreen mode

Note: The order and number of arguments passed must match the function's parameters.

2.2 Keyword Arguments

This involves passing arguments to the function using the "key=value" format.

Purpose: Makes the function clearer and easier to use, and removes the requirement for arguments to be in a specific order.

def user_info(name, age, gender):
    print(f"Your name is: {name}, age is {age}, gender is {gender}")
# Keyword arguments
user_info(name="Alex", age=18, gender="male")
# Order doesn't need to be fixed
user_info(age=22, gender="female", name="Xiao Mei")
# Can mix with positional arguments, positional must come first
user_info("Echo", age=21, gender="female")
Enter fullscreen mode Exit fullscreen mode

Note: When calling a function, if positional arguments are used, they must precede keyword arguments. Keyword arguments themselves can be in any order.

2.3 Variable-Length Arguments

Variable-length arguments, also called varargs, are used when the number of arguments passed to the function is unknown (it can even be zero).

Purpose: Useful for cases where the number of arguments to be passed is uncertain.

Types of variable-length arguments:

  1. Positional
  2. Keyword

Positional:

# Variable-length positional arguments
def user_info(*args):
    print(args)
user_info("tom")  # Output: ('tom',)
user_info("tom", 18)  # Output: ('tom', 18)
Enter fullscreen mode Exit fullscreen mode

Note: All arguments passed are collected into the args variable, forming a tuple (args is of tuple type). This is positional passing of arguments.

Keyword:

# Variable-length keyword arguments
def user_info(**kwargs):
    print(kwargs)
user_info(name="tom", age=18, id=110)  # Output: {'name': 'tom', 'age': 18, 'id': 110}
Enter fullscreen mode Exit fullscreen mode

Note: When arguments are passed in the "key=value" format, they are collected into the kwargs variable, forming a dictionary.

2.4 Default Arguments

Default or optional arguments are used to provide default values for parameters. If these parameters are not supplied during the function call, they default to the specified values. (Note: All positional arguments must come before any default arguments in both the function definition and the call.)

Purpose: If the function is called without certain arguments, it uses the default values.

# Default arguments
def user_info(name, age, gender="male"):
    print(f"Your name is: {name}, age is {age}, gender is {gender}")
user_info("tom", 20)
user_info("rose", 22, "female")
Enter fullscreen mode Exit fullscreen mode

3. Anonymous Functions

3.1 Functions as Arguments

Previously, we have passed data (numbers, strings, dictionaries, tuples, lists, etc.) as arguments to functions. However, a function itself can also be passed as a parameter to another function.

For example:

# Function as an argument
def test_func(compute):
    result = compute(1, 2)
    print(result)
def compute(x, y):
    return x + y
test_func(compute)
Enter fullscreen mode Exit fullscreen mode

The compute function is passed as an argument to the test_func function.

  • test_func requires a function as an argument that accepts two numbers and performs a calculation, with the calculation logic defined by the passed-in function.
  • The compute function takes two numbers and performs a calculation. This function is then passed to test_func.
  • Inside test_func, the passed-in compute function performs the calculation.

Thus, we are passing the logic of the calculation, not the data itself. Any custom logic can be defined and passed as a function.

3.2 Lambda Anonymous Functions

Function definitions:

  • The def keyword defines named functions.
  • The lambda keyword defines anonymous (unnamed) functions.

Named functions can be reused based on their name; unnamed lambda functions are utilized only once temporarily.

Anonymous function syntax:

lambda parameters: single-line expression
Enter fullscreen mode Exit fullscreen mode
  • lambda is the keyword for defining anonymous functions.
  • The parameters are the function’s input, similar to formal parameters like x, y, etc.
  • The function body is the execution logic, limited to a single line.

Example:

# Lambda anonymous function
def test_func(compute):
    result = compute(1, 2)
    print(result)
test_func(lambda x, y: x + y)
# Note: Lambda functions cannot be reused
Enter fullscreen mode Exit fullscreen mode

So far, we're halfway through the "Learn Python in 10 Days" series and hope it's been helpful. By the way, check out our team's new Postman alternative EchoAPI. We'd love your feedback! 😊

Best Postman Alternatives for 2024

Top comments (0)