Python Functions: Modular, Reusable Code Blocks
A function is a reusable block of code that performs a specific task. You define it once, give it inputs (parameters), perform logic, and return a result. Functions keep code modular, testable, and maintainable.
"A function is like a kitchen blender. You pour ingredients in (parameters), press the button (execute code), and pour out a delicious smoothie (return value). You can use the blender 50 times without having to reinvent it."
Deep Dive: How It Works
Return Type: The data type of the result (e.g. int, double, void if returning nothing).
Parameters: Inputs accepted by the function (e.g. int a, int b).
Function Prototypes: In C++, functions must be declared or defined BEFORE they are called. If a function is written below main(), declare its prototype above main(): int add(int a, int b);.
void Functions: Functions that perform actions (like printing) without returning a value.
Syntax Blueprint
// ReturnType FunctionName(Parameters) {
// Body
// return value;
// }
int multiply(int a, int b) {
return a * b;
}Define return type, name, input parameters, and return statement.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting to return a value from a non-void functionWhy it happens: Forgetting return result; at the end of an int function.
How to fix: All non-void functions must return a value matching their declared type.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Write a square function
Write an int square(int x) function that returns x * x.
In main(), print "Square of 6 is 36" by calling square(6).
Finished reading and practicing?
Mark this lesson as completed to update your course progress.