Basic Function Definition
Create a simple function that returns a greeting.
Functions are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs more modular and maintainable.
π Concepts & Theory
Functions in Python are defined using the def keyword, followed by the function name, parentheses, and a colon. The function body is indented.
Basic Function Syntax:
def function_name():
# function body
return value
Function Components:
- def keyword: Declares a function
- Function name: Should be descriptive (use snake_case)
- Parentheses (): Hold parameters (empty if none)
- Colon : Starts the function body
- Indentation: Defines the function scope
- return statement: Sends value back to caller
def greet():
return "Hello, World!"
message = greet() # Calls the function
print(message) # "Hello, World!"
Functions Without Return:
def print_message():
print("This function doesn't return anything")
# Implicitly returns None
Why Use Functions:
- Code Reusability: Write once, use many times
- Organization: Break complex problems into smaller parts
- Readability: Named functions describe what they do
- Testing: Easier to test isolated functions
- Maintenance: Change logic in one place
- Use lowercase with underscores (snake_case)
- Be descriptive:
calculate_total()notcalc() - Verbs for actions:
get_user(),send_email()
The
return statement exits the function and sends a value back:def add_five(n):
return n + 5 # Exits here, sends result back
result = add_five(10) # result = 15
Functions are fundamental to writing clean, maintainable Python code.
π― Your Challenge
Create a function named greet() that returns the string "Hello, World!"
π Starter Code
def greet():
pass
- Start with the def keyword
- Function name should be greet with empty parentheses
- The function body must be indented
- Use return to send back a value
- Return the exact string: Hello, World!
Solution
def greet():
return "Hello, World!"
Explanation
The function uses the return statement to send back the string "Hello, World!" to the caller. When you call greet(), it executes the function body and returns this exact string. The return keyword is crucialβwithout it, the function would return None by default. This demonstrates the fundamental structure of Python functions: definition with def, function name, empty parameters, and a return value.
β οΈ Common Mistakes to Avoid
- Forgetting the return statement (function returns None)
- Not calling the function with parentheses ()
- Indentation errors in function body
- Using print() instead of return
- Forgetting the colon after function definition