YouTip LogoYouTip

Python Functions and Modules

Defining Functions

# Basic function
def greet(name):
    return f"Hello, {name}!"

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

# Function with no return
def print_info(name, age):
    print(f"{name} is {age} years old")

# Returns None implicitly

Default and Keyword Arguments

# Default parameters
def power(base, exponent=2):
    return base ** exponent

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

# Keyword arguments
def user_info(name, age, city):
    print(f"{name}, {age}, {city}")

user_info(city="Tokyo", name="Bob", age=30)

*args and **kwargs

# Variable number of arguments
def sum_all(*args):
    return sum(args)

print(sum_all(1, 2, 3, 4))  # 10

# Keyword arguments as dictionary
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="Singapore")

Lambda Functions

# Anonymous one-line functions
square = lambda x: x ** 2
print(square(5))  # 25

add = lambda a, b: a + b
print(add(3, 4))  # 7

# Common use: sorting
students = [("Alice", 90), ("Bob", 85), ("Charlie", 92)]
students.sort(key=lambda s: s)  # sort by score

Modules

# Import a module
import math
print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.14159...

# Import specific
from math import sqrt, pi
print(sqrt(16))

# Import with alias
import numpy as np

# Create your own module
# mymodule.py
def add(a, b):
    return a + b

# main.py
import mymodule
print(mymodule.add(3, 5))

Built-in Functions

# Common built-in functions
print(len("hello"))     # 5
print(max(1, 2, 3))     # 3
print(min(1, 2, 3))     # 1
print(abs(-5))           # 5
print(round(3.7))        # 4
print(sorted([3,1,2]))   # [1, 2, 3]
print(type(42))          # <class "int">
print(isinstance(42, int))  # True

Summary

  • Functions are defined with def, anonymous functions with lambda
  • Default arguments provide fallback values
  • *args collects positional arguments, **kwargs collects keyword arguments
  • Modules organize code into reusable files
← Python File HandlingPython Control Flow - If and L β†’