Functions
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Functions
Definition: A function is a named, reusable block of code that only runs when it is explicitly called. You can pass data (parameters) into a function, and it can send data (return values) back as a result.
Why: Functions are a critical programming topic because they stop you from writing the same code over and over again. They break large, complicated programs down into smaller, organized, and much more readable pieces.
Syntax
def function_name(parameters):
# code to execute
return value
Example
def add(a, b):
return a + b
# Calling the function and storing the result
result = add(10, 20)
print(result)
Explanation
- The
defKeyword: This tells Python that you are defining a new function. - Parameters:
aandbare placeholders for the data that the function expects to receive when it is used. - The
returnKeyword: This exits the function and sends the calculated result back to the line where the function was called. - Function Call:
add(10, 20)passes the actual numbers 10 and 20 into the function, which returns 30 to be stored in theresultvariable.
Key Notes
- Defining a function does not run it. The code inside will only execute when you "call" or invoke the function by its name followed by parentheses (e.g.,
function_name()). - Functions do not strictly require a
returnstatement. If no return is specified, the function automatically returnsNone. - A function must be defined higher up in your script before you try to call it.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute