Python 24-Day Course - Day 8: Function Basics

Day 8: Function Basics

Defining and Calling Functions

def greet(name):
    """Greets the user."""
    return f"Hello, {name}!"

message = greet("Alice")
print(message)  # Hello, Alice!

Parameter Types

# Default parameter
def power(base, exp=2):
    return base ** exp

print(power(3))      # 9
print(power(3, 3))   # 27

# Keyword arguments
def profile(name, age, city="Seoul"):
    return f"{name}, age {age}, {city}"

print(profile(age=25, name="Bob"))
# Bob, age 25, Seoul

Returning Multiple Values

def min_max(numbers):
    return min(numbers), max(numbers)

lowest, highest = min_max([3, 1, 4, 1, 5, 9])
print(f"Min: {lowest}, Max: {highest}")
# Min: 1, Max: 9

Scope (Variable Scope)

global_var = "global"

def my_func():
    local_var = "local"
    print(global_var)   # Can read global variable
    print(local_var)    # Local variable

my_func()
# print(local_var)  # NameError: cannot access outside the function

Docstring

def calculate_bmi(weight, height):
    """Calculates BMI.

    Args:
        weight: Weight in kg
        height: Height in meters

    Returns:
        BMI value (float)
    """
    return weight / (height ** 2)

Today’s Exercises

  1. Write a function that finds the greatest common divisor (GCD) of two numbers.
  2. Write a function that returns the mean, variance, and standard deviation of a list.
  3. Create a temperature conversion function (Celsius to Fahrenheit and vice versa, with direction as a parameter).

Was this article helpful?