Introduction
Functions help us organize code into small, reusable pieces. They make programs easier to read, write, and fix.
Jump into concepts and practice - no test required
Functions help us organize code into small, reusable pieces. They make programs easier to read, write, and fix.
def function_name(parameters): # code to do something return result # optional
Use def to start a function.
Functions can take inputs called parameters and can send back a result with return.
def greet(): print("Hello!")
def add(a, b): return a + b
def is_even(number): return number % 2 == 0
This program shows two functions: one to say hello and one to add numbers. We call them to see how they work.
def greet(): print("Hello, friend!") def add(a, b): return a + b # Use the greet function print("Calling greet function:") greet() # Use the add function result = add(5, 7) print(f"5 + 7 = {result}")
Functions help avoid repeating the same code many times.
Giving functions clear names makes your code easier to understand.
You can change how a function works without changing the rest of your program.
Functions organize code into reusable blocks.
They make programs easier to read and fix.
Functions let you break big problems into smaller steps.
def, followed by the function name and parentheses.def correctly to define a function.def greet():
print('Hello!')
greet()
greet()greet() prints 'Hello!' each time it is called.greet() twice, so 'Hello!' prints two times.def add_numbers(a, b)
return a + b
result = add_numbers(3, 4)
print(result)def add_numbers(a, b), causing syntax error.