Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Functions Module 4 - Functions Python Python Basics Python Programming: From Zero to Real-World Applications

Defining Functions in Python - def, Parameters, return

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How to define and call functions
  • Parameters and return values
  • Docstrings for documentation
Terminalpython
# Basic function
def greet(name):
    return f"Hello, {name}!"

# Call the function
message = greet("Anita")
print(message)   # Hello, Anita!

# Function with multiple parameters
def add(a, b):
    return a + b

result = add(5, 3)
print(result)   # 8

# Function with no return (returns None)
def print_greeting(name):
    print(f"Hi, {name}!")

result = print_greeting("Ravi")   # Prints: Hi, Ravi!
print(result)                      # None

Docstrings

Terminalpython
def calculate_area(length, width):
    """Calculate the area of a rectangle.
    
    Args:
        length: The length of the rectangle
        width: The width of the rectangle
    
    Returns:
        The area (length * width)
    """
    return length * width

# Access docstring
print(calculate_area.__doc__)
Functions are reusable blocks
If you write the same code twice, put it in a function. Functions make code: reusable, testable, readable, and maintainable.

Practical Exercise

Define: def greet(name): return f"Hello, {name}!"
Call: greet("Anita")
Define: def add(a, b): return a + b
Add a docstring to your function
Call help(greet) to see the docstring

Key Takeaways

  • Define with def. Call with function_name(args).
  • return sends a value back. No return = returns None.
  • Parameters receive values. Multiple params separated by commas.
  • Docstrings (triple quotes) document your function.
  • If code is repeated, put it in a function.
Previously: Module 3 covered data structures.
Today: You learned: Write reusable code with functions.
Next: Lesson 25 covers default args.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments