Organizing Code into Reusable Blocks
Benefits:
Example:
# Without functions (repetitive)
print("Welcome to our store!")
print("Thank you for shopping!")
print("Welcome to our store!")
print("Thank you for shopping!")
# With functions (clean)
def welcome_message():
print("Welcome to our store!")
print("Thank you for shopping!")
welcome_message()
welcome_message()Key Components:
def keyword starts the function definitionfunction_name follows Python naming conventionsparameters are inputs (optional): indicates the start of the function bodyreturn statement provides output (optional)Function with no parameters:
Single parameter:
Parameters can have default values:
Call functions using parameter names:
*args for variable positional arguments:
Variables inside functions are local:
Functions can return any data type:
Document your functions:
def add(a, b):
"""Add two numbers."""
return a + b
def subtract(a, b):
"""Subtract second number from first."""
return a - b
def multiply(a, b):
"""Multiply two numbers."""
return a * b
def divide(a, b):
"""Divide first number by second."""
if b != 0:
return a / b
else:
return "Error: Division by zero!"
# Using the calculator
result1 = add(10, 5) # 15
result2 = subtract(10, 5) # 5
result3 = multiply(10, 5) # 50
result4 = divide(10, 5) # 2.0Challenge 1: Temperature Converter
Temperature Converter:
calculate_tax() not calc()1. Modifying mutable defaults:
Coming up next: - Error handling and exceptions - Working with modules and packages - Object-oriented programming
Practice more: - Create a simple menu system using functions - Build a text-based game with multiple functions - Write functions for common mathematical operations
Python Tutorial