Week Four
This week we learn about functions — named blocks of code that perform a task and can be reused throughout your program.
Presentation
Functions
A function is a named block of code that performs a task. Functions help you organize your code and reuse code instead of writing the same instructions again.
Function Syntax
Functions in Python follow a specific structure:
def function_name():
# code inside the functiondeftells Python you are defining a functionfunction_nameis the name you choose (use lowercase and underscores)- The parentheses
()are required - The colon
:tells Python the function code is starting - All lines inside the function must be indented
Defining a Function
def say_hello():
print("Hello!")This defines the function but does not run it yet.
Indentation Matters
Python uses indentation to know which lines belong to a function.
def show_message():
print("This line is inside the function")
print("This line is outside the function")Only the indented line runs when the function is called.
Calling a Function
To run a function, write its name followed by parentheses.
say_hello()The code inside the function runs from top to bottom.
Functions Can Have Multiple Lines
def start_program():
print("Program starting...")
print("Loading...")
print("Ready!")
start_program()Why Functions Are Useful
- Organize code
- Reduce repetition
- Make programs easier to read
- Control when code runs
Functions group instructions together so you can use them whenever you need.
Modules
A module is a file that contains extra code you can use in your program. Modules let you use features that are already written, instead of creating everything from scratch.
Python comes with many built-in modules.
Importing a Module
To use a module, you must import it first.
import randomThis gives your program access to everything inside the random module.
Using a Module
After importing, you use the module name followed by a dot . and the function you want.
import random
number = random.randint(1, 10)
print(number)random.randint(1, 10)gives a random number between 1 and 10
Why Modules Matter
- Save time
- Keep code clean
- Use powerful tools easily
- Share code between programs