A function is a reusable piece of code that performs a specific task. We define it with def, followed by a name and optional parameters. Inside, we can use return to give back a result.
Our learning goals are understanding that a function is a reusable block of code with a name, optional parameters, and an optional return value; learning the basic syntax def name(parameters): ... return value, and writing simple functions (no-parameter, with parameters, with return).
A function is like teaching your computer a small skill. You bundle several steps, give that bundle a name, and later call the name to run those steps. You may pass inputs (parameters), and the function can give a result back (return value). Functions let us split big programs into clean, reusable modules.
Syntax & Key Points:
def function_name(parameters):
# body (indented)
return value
Example A: No Parameter, No Return
def hello():
print("Hello, world!")
hello()
Output example A:
Hello, world!
Example B: With Parameter, No Return
def greet(name):
print("Hello,", name)
greet("Alice")
greet("Bob")
Output example B:
Hello, Alice
Hello, Bob
Example C: With Parameters and Return
def add(a, b):
return a + b
s = add(3, 5)
print("Sum =", s)
Output example C:
Sum = 8
Common Confusion: print() vs return
print(): Displays information on the screen, mainly “for people to see”return: Sends data back to the program, mainly “for the computer to use later”Example D: print() vs return
def wrong_add(a, b):
print(a + b)
x = wrong_add(2, 3)
print("x is", x)
Output example D:
5
x is None
Common Pitfalls:
print() doesn’t give a result. You need return to pass data back for further use.calc_total, is_even) to make the code readable and maintainable.Now that we know what a function is and how it looks, let’s go deeper: let functions accept different inputs and return reusable results—so our programs become easy to extend, like building with blocks.