Lesson: Functions in Python ( by prompt AI teaching assistant)

 

Lesson: Functions in Python

[introduction]

Welcome back! Today we’re learning functions, one of the most important concepts in all of programming. After this lesson, you’ll understand what functions are, why they’re useful, how to create them, and how to use them effectively.


[concept_explanation]

A function is a reusable block of code that performs a specific task.
Instead of writing the same code repeatedly, you define a function once and call it whenever you need it.

Functions help you:

  • Organize your code

  • Avoid repetition

  • Make your programs cleaner and easier to understand

  • Break large problems into smaller, manageable parts

In Python, you define a function using the def keyword.

Key components of a function:

  1. Function name

  2. Parameters (optional)

  3. Function body

  4. Return value (optional)

Basic structure:

def function_name(parameters): # code to execute return value

[python_examples]

1. A simple function

def greet(): print("Hello!")

Calling it:

greet()

2. Function with a parameter

def say_hello(name): print("Hello,", name)

Calling it:

say_hello("Alex")

3. Function that returns a value

def add(a, b): return a + b result = add(5, 3) print(result)

4. Function with multiple steps

def describe_person(name, age): message = f"{name} is {age} years old." return message print(describe_person("Mia", 20))

[analogy]

Think of a function like a vending machine:

  • You press a button (call the function)

  • You may insert something (parameters)

  • The machine performs a process internally (function body)

  • You get something out (return value)


[practice_task]

Try writing the following functions:

  1. A function called welcome() that prints “Welcome to Python!”.

  2. A function called square(num) that returns the square of a number.

  3. A function introduce(name, hobby) that prints a sentence about someone’s hobby.


[quiz]

  1. What keyword is used to define a function in Python?

  2. What is the difference between a parameter and an argument?

  3. What will this function return?

def mystery(x): return x * 2 print(mystery(4))

[common_mistakes]

  • Forgetting to call the function (writing it but never using it).

  • Forgetting parentheses when calling the function.

  • Trying to print a function that returns nothing.

  • Mixing up returning a value vs printing a value.


[extra_notes]

  • If a function does not have a return statement, it returns None by default.

  • Python allows default parameters, like:

    def greet(name="friend"): print("Hello,", name)
  • Functions support keyword arguments and positional arguments, giving flexibility in how you call them.

Comments

Popular posts from this blog

Ecommerce website

Yes, Python is an object-oriented programming (OOP) language, but it is also a multi-paradigm language

Your task is to find the missing number.