About 2302 letters

About 12 minutes

#Python's function creation and call

When writing programs, there are often many similar pieces of code. For example, in a game battle, the damage calculation formula might be:

We just need to provide the values of attack power and defense power each time to calculate damage. This calculation formula can be reused by defining a function.

How to define and call a function:

# Define function
def function_name(parameter1, parameter2, ...) -> return_type:
    function_body

# Call function
function_name(argument1, argument2, ...)

Functions can have no parameters and no return values. If no return value is specified, the function returns None.

The above damage formula can be encapsulated as:

# Define function
def attack(attack_power: float, defense_power: float):
    # Calculate damage
    damage: float = attack_power * (1 - defense_power / (defense_power + 100))
    print(f"Dealt {damage} points of damage")

# Call function
attack(100, 0)
attack(100, 10)
attack(100, 20)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Return values

Return values are returned using the return keyword, for example:

def attack(attack_power: float, defense_power: float) -> float:
    # Calculate damage
    damage: float = attack_power * (1 - defense_power / (defense_power + 100))

    # Return damage
    return damage

# Receive return value
damage: float = attack(100, 0)
print(f"Damage is {damage}")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Functions can return multiple values, but in fact they return a tuple, for example:

def attack(attack_power: float, defense_power: float) -> tuple[float, float]:
    # Calculate damage reduction by defense
    guard: float = attack_power * defense_power / (defense_power + 100)
    # Actual damage dealt
    damage: float = attack_power - guard

    # Equivalent to returning (damage, guard) as a tuple
    return damage, guard

# Unpack returned tuple
damage, guard = attack(100, 20)
print(f"Damage is {damage}, defense reduced damage by {guard}")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025