Creating Reusable Functions

Functions encapsulate logic into reusable units, making code more organized and maintainable. Mastering functions is crucial for building complex programs.

Function Structure

def greet(name):
"""Returns personalized greeting"""
return f"Hello, {name}!"
print(greet("Alice")) # → Hello, Alice!
Hello, Alice!
Key components:
  • def keyword starts function definition
  • Parentheses contain parameters
  • Colon ends declaration line
  • Indented body block

Return Mechanism

def is_positive(n):
return n > 0
print(is_positive(5)) # → True
print(is_positive(-3)) # → False
True\nFalse

Common Errors

# Forgetting return statement
def add(a, b):
a + b # No return → returns None
# Incorrect indentation
def wrong(): print("Oops") # IndentationError

Practical Use: Password Checker

def is_strong(password):
"""Checks if password has ≥8 chars and numbers"""
return len(password) >= 8 and any(c.isdigit() for c in password)
print(is_strong("pass123")) # → True
print(is_strong("weak")) # → False
True\nFalse

Your Task: Even Number Checker

Complete the is_even function:

  1. Take integer n as parameter
  2. Return True if even, False otherwise
  3. Test with numbers 1-5

Remember: Even numbers have no remainder when divided by 2.

Section 1/5Function Structure

Function Structure

Explore this concept

Creating Reusable Functions

Functions encapsulate logic into reusable units, making code more organized and maintainable. Mastering functions is crucial for building complex programs.

Function Structure

def greet(name):
"""Returns personalized greeting"""
return f"Hello, {name}!"
print(greet("Alice")) # → Hello, Alice!
Hello, Alice!
Key components:
  • def keyword starts function definition
  • Parentheses contain parameters
  • Colon ends declaration line
  • Indented body block

Output:

Click "Check" to run your code.