Introduction to Functions
Learn how to write reusable blocks of code using functions
Learning Objectives
- Understand the purpose of functions
- Define and call basic functions
- Use parameters and arguments
- Return values from functions
Why Functions?
Imagine you are writing a program that greets a user. You might write:
|
|
If you have 100 users, you don’t want to write that line 100 times. Instead, you create a Function.
A function is a reusable block of code that performs a specific task. You define it once, and you can “call” it whenever you need it.
Defining a Function
In Python, we use the def keyword to define a function.
|
|
Key Rules:
- Use the
defkeyword. - Give the function a name (use lowercase and underscores).
- Add parentheses
()and a colon:. - Indent the code block inside the function.
Parameters and Arguments
Functions become powerful when they can accept information. We use parameters to pass data into a function.
|
|
usernameis the parameter (the variable name inside the function)."Alice"is the argument (the actual value passed in).
Returning Values
Sometimes you want a function to calculate something and give the result back to you. We use the return statement for this.
|
|
print() displays text on the screen. return sends data back to the part of the program that called the function, so you can store it in a variable.Interactive Practice
Try defining a function called multiply that takes two numbers and returns their product.
Quiz
Complete this quiz with a minimum score of 80% to mark Day 8 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!