We have just learned how to define and call functions. There's a little more to it though!
1. Ensure that you are signed into GitHub
Open the assignment: Project 4 - Dice Roller
Open lab2.py
In programming, functions often need specific information to perform their task. This information comes in the form of parameters and arguments, which allow functions to be more flexible and reusable.
A parameter is like a placeholder in a function; it's a variable listed in a function definition. When a function is called, the values you pass to it are known as arguments. These arguments fill the placeholders represented by parameters.
For example, when you use the print() function in Python, you've been providing arguments without necessarily realising it. The print() function is designed to accept arguments which are the values you want to display.
Parameters take our functions to the next level by allowing us to customise the function's behaviour each time we call it. They make our code more modular and dynamic.
Parameter: A variable in the declaration of the function. It's what the function expects.
Argument: The actual value that is passed to the function when it is called. It's what you give to the function.
Simply include the variable name inside the parenthesis. In the example below:
We include one parameter called 'name'
The argument "Alice" is passed to the greet function when it is called
Simply separate the parameters with commas. In the example below:
We include two parameters: 'first_name' and 'last_name'
The arguments "Ada" and "Lovelace" are passed to the full_name function when it is called
The order in which parameters are listed corresponds to the order in which arguments should be passed to the function when it is called
Complete the following requirements:
Create a function named say_hello that accepts a person's name as a parameter and prints "Hello" followed by the name.
Develop a function named triple that takes one number as a parameter and returns the number multiplied by three.
Write a function called add that takes two numbers as parameters and returns their sum.
Create a function named draw_line that takes one parameter for the length of the line and prints a straight line of that many hyphens.
Call your functions, printing out the return result where appropriate
Press Ctrl + F5 to run the program or open a terminal and type python lab2.py
You should now be able to write functions that perform tasks, use inputs (parameters), and give back results (return values). You should also understand the difference between parameters and arguments.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 2 complete"
Press Commit to main
Press Push origin