WHAT ARE PROCEDURES AND FUNCTIONS
When parts of your program repeatedly run, functions and procedures create a solution where you can create a small block of code, give that block of code a name and call it to run when ever you need it.
SECTION 1 | PROCEDURES AND FUNCTIONS
A procedure performs a task and does not necessarily return any values, where are a function would return values for elsewhere in the program to use. For example a procedure might be to draw a square, a function might be to ask the user their name and return the result in a string.
Decomposition is the term used for breaking large tasks down into small manageable pieces, we use functions and procedures as a way of writing code in individual pieces which then allows us to run the same piece of code multiple times within a program and allow us to easily navigate tasks within our program. You should look at using decomposition to break your program down in to small functions and procedures, even if you think you don't need them it is good practice and will help build your programming skills.
Decomposition is the term used for breaking large tasks down into small manageable pieces, we use functions and procedures as a way of writing code in individual pieces which then allows us to run the same piece of code multiple times within a program and allow us to easily navigate tasks within our program. You should look at using decomposition to break your program down in to small functions and procedures, even if you think you don't need them it is good practice and will help build your programming skills.
SECTION 2 | PROCEDURES
A procedure allows you to produce a block of code that can be used many times to repeat an action or operation. For example look at the block of code below drawing a text cat.
print (" ^___^ ")
print (" / o o \ ")
print ("=\ ' /=")
print (" \ - / ")
With normal coding if you wanted to draw 2 cats you would need to copy and paste the code, this is not an ideal solution with large projects. A better solution is to create a procedure to draw the cat whenever you need it. Below is an example of a procedure to do this.
print (" ^___^ ")
print (" / o o \ ")
print ("=\ ' /=")
print (" \ - / ")
With normal coding if you wanted to draw 2 cats you would need to copy and paste the code, this is not an ideal solution with large projects. A better solution is to create a procedure to draw the cat whenever you need it. Below is an example of a procedure to do this.
In the code above broken down:
- def defines the function
- myCat is the name given to the function - the same naming conventions for procedures as for variables
- () are needed to receive any parameters - discussed in functions
- : simply means DO
- The program is then indented into the procedure, this indentation lets Python know what is inside the procedure and when it ends
- myCat() calls the procedure - the command to run the procedure
SECTION 3 | FUNCTIONS
Functions use the same principles as procedures however functions return values to back outside the function. Functions are discrete entities of code and variable inside the function are not the same as the variables outside the function. It is very temping to create global function to solve the problem of passing values in to and out of a function however this should be avoided where possible.
Global variables can be manipulated within functions, however the variable needs to be defined as global when creating the variable and it is not seen as good practice to use global variables unless a team of coding engineers have collectively decided on the global variables needed for a particular project, using global variables can get messy when multiple people are working on the same coding project unless strict rules are followed.
Local variables are the variables we have been using so far in this Python section. Local variables that are set outside of a function can be seen from inside the function but any changes made inside the function will not be seen outside of the function.
Take a look at the code below, what would you expect to happen ?
def myNum():
num1 = (5)
myNum()
print (num1)
The function runs, but num1 is only created inside the function, so on the last line of code where num1 is called, it will create an error: NameError: name 'num1' is not defined. num1 is clearly define but only within the function. This is where return methods and passing parameter is required.
Global variables can be manipulated within functions, however the variable needs to be defined as global when creating the variable and it is not seen as good practice to use global variables unless a team of coding engineers have collectively decided on the global variables needed for a particular project, using global variables can get messy when multiple people are working on the same coding project unless strict rules are followed.
Local variables are the variables we have been using so far in this Python section. Local variables that are set outside of a function can be seen from inside the function but any changes made inside the function will not be seen outside of the function.
Take a look at the code below, what would you expect to happen ?
def myNum():
num1 = (5)
myNum()
print (num1)
The function runs, but num1 is only created inside the function, so on the last line of code where num1 is called, it will create an error: NameError: name 'num1' is not defined. num1 is clearly define but only within the function. This is where return methods and passing parameter is required.
SECTION 4 | RETURN A VALUE
The return statement is used to exit a function and go back to the place from where it was called. More importantly, it allows a function to "send back" a result to the caller. This result can be a value, an expression, or even multiple values.
Why Use return?
Why Use return?
- To Get a Value: Functions can perform a task and send the result back to the caller. This is useful when you want to use the result of a function elsewhere in your code.
- To Exit Early: You can use the return statement to exit a function prematurely based on certain conditions.
Here, the get_info function returns two values: name and age. When calling the function, we can unpack these values into two separate variables, in this case the return is stored in the variables 'person_name' and 'person_age'.
The example below shows how the return method can be used to exit a function early and how different return values can be returned based on a condition(IF statemtent).
The example below shows how the return method can be used to exit a function early and how different return values can be returned based on a condition(IF statemtent).
- A function can have multiple return statements, but as soon as one is executed, the function will exit, and no subsequent lines in that function will be executed.
- If a function doesn't have a return statement or if the return statement doesn't have an expression, the function will return None by default.
- You can return any data type from a function, including lists, dictionaries, tuples, and even other functions.
The return statement in Python functions allows you to send results back to the caller, making functions more versatile and useful in various programming scenarios
SECTION 5 | PASSING PARAMETERS
In Python, functions can take inputs, known as parameters or arguments, to perform specific tasks based on those inputs. You can define a function with parameters by placing the parameter names inside the parentheses of the function definition.
PASSING PARAMENTER
In the example above, name is a parameter of the greet function. When calling the function, we pass the argument "Alice" to it.
Arguments passed to a function in the exact order in which they are defined are called positional arguments. This is because it is the position that the arguments are placed in the brackets that is inherited, not the variable name.
Arguments passed to a function in the exact order in which they are defined are called positional arguments. This is because it is the position that the arguments are placed in the brackets that is inherited, not the variable name.
POSITIONAL ARGUMENTS
You can provide default values to parameters. If an argument for that parameter is not provided when calling the function, the default value is used.
DEFAULT ARGUMENTS
You can pass arguments using the parameter values, allowing you to place them out of order.
KEYWORD ARGUMENTS
If you're unsure about the number of positional arguments you might need to pass, you can use *args. It collects extra arguments as a tuple. To do this use the Asterix * before the receiving variable.
ARGS*
For an arbitrary number of keyword arguments, use **kwargs. It collects extra keyword arguments as a dictionary. Taking the variable name as the 'key' and the value stored in the variable as the value.
**KWARGS
You can pass lists, dictionaries, and other data structures as arguments to functions.
LISTS AND DICTIONARIES
Unlike strings, int, floats and tuple, when you pass a mutable object(list, dictionary, set) to a function and modify its value within the function, it will affect the original object. This is because both the variable inside the function and the original object reference the same object in memory.
PASS BY REFERENCE
ELEMENT |
DESCRIPTION |
EXAMPLE |
Defining Functions |
Functions are blocks of reusable code. They are defined using the def keyword. |
def greet(name): return f"Hello, {name}!" print(greet("Alice")) # Outputs: Hello, Alice! |
Positional Arguments |
Functions can take arguments (inputs) and return values (outputs). Positional Arguments: Arguments passed in order. |
def add(x, y): return x + y |
Keyword Arguments |
Keyword Arguments are Arguments passed by name. |
def print_info(name, age): print(f"Name: {name}, Age: {age}") print_info(age=30, name="John") |
Default Arguments |
Default Arguments are Arguments with default values. |
def greet(name="Guest"): return f"Hello, {name}!" print(greet()) # Outputs: Hello, Guest! |
Return Values |
Use the return keyword to send a result back |
def square(num): return num * num result = square(4) # result is 16 |
*args |
*args allows you to pass a variable number of positional arguments to a function. Inside the function, args is a tuple containing all passed arguments. |
def add_numbers(*args): return sum(args) print(add_numbers(1, 2, 3, 4)) # Outputs: 10 |
*kwargs |
**kwargs allows you to pass a variable number of keyword arguments to a function. Inside the function, kwargs is a dictionary containing all passed keyword arguments. |
def print_data(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_data(name="John", age=30, country="USA") # Outputs: # name: John # age: 30 # country: USA |
ASCII DRAWING
1: Create a drawing in Python using only text charters (like the cat above, but better!)
2: Create a procedure and place your drawing in the procedure
3: Repeat steps 1 and 2 this time drawing a different object.
4: Call/run your procedures to draw the first, then the second then the first object again.
2: Create a procedure and place your drawing in the procedure
3: Repeat steps 1 and 2 this time drawing a different object.
4: Call/run your procedures to draw the first, then the second then the first object again.
ARGUMENTS WITH FUNCTIONS
QUESTION
1: Take a look at the following code; what do you think will happen.
1: Take a look at the following code; what do you think will happen.
TASK
1: Copy the code and make the corrections needed for the code to work as expected.
NOTE: The output returned from the function and printed should be 5
1: Copy the code and make the corrections needed for the code to work as expected.
NOTE: The output returned from the function and printed should be 5
SIMPLE EXPENSE TRACKER
OBJECTIVES
Create a program that allows a user to track their expenses. The user should be able to add an expense, view all expenses, and calculate the total amount spent. Use functions for each menu option.
TASKS
1: Add an Expense
Prompt the user for the name of the expense (e.g., "Groceries", "Rent", "Utilities").
Prompt the user for the amount of the expense.
Store the expense name and its amount.
2: View All Expenses
Display a list of all added expenses along with their amounts.
3: Calculate the Total
Calculate and display the total amount spent based on all the expenses added.
4: User Menu - Provide a menu for the user where they can choose to:
Add an expense.
View all expenses.
Calculate the total amount spent.
Exit the program.
Hints
Use an array to store the expenses.
Each expense can be an object with properties for the name and amount.
Use functions to encapsulate the logic for each menu option.
SAMPLE OUTPUT
Welcome to the Expense Tracker!
Menu:
1. Add an Expense
2. View All Expenses
3. Calculate Total Amount Spent
4. Exit
Choose an option: 1
Enter the name of the expense: Groceries
Enter the amount: 50
Expense added successfully!
Menu:
1. Add an Expense
2. View All Expenses
3. Calculate Total Amount Spent
4. Exit
Choose an option: 2
Expenses:
- Groceries: $50
Menu:
... (and so on)
Create a program that allows a user to track their expenses. The user should be able to add an expense, view all expenses, and calculate the total amount spent. Use functions for each menu option.
TASKS
1: Add an Expense
Prompt the user for the name of the expense (e.g., "Groceries", "Rent", "Utilities").
Prompt the user for the amount of the expense.
Store the expense name and its amount.
2: View All Expenses
Display a list of all added expenses along with their amounts.
3: Calculate the Total
Calculate and display the total amount spent based on all the expenses added.
4: User Menu - Provide a menu for the user where they can choose to:
Add an expense.
View all expenses.
Calculate the total amount spent.
Exit the program.
Hints
Use an array to store the expenses.
Each expense can be an object with properties for the name and amount.
Use functions to encapsulate the logic for each menu option.
SAMPLE OUTPUT
Welcome to the Expense Tracker!
Menu:
1. Add an Expense
2. View All Expenses
3. Calculate Total Amount Spent
4. Exit
Choose an option: 1
Enter the name of the expense: Groceries
Enter the amount: 50
Expense added successfully!
Menu:
1. Add an Expense
2. View All Expenses
3. Calculate Total Amount Spent
4. Exit
Choose an option: 2
Expenses:
- Groceries: $50
Menu:
... (and so on)
Question 1: Structure of If Statements
EXPLANATION
Question 2: Importance of if-else Statements
EXPLANATION
Question 3: Nested If Statements
EXPLANATION
Question 4: Using elif Instead of Multiple if Statements
EXPLANATION
Question 5: Best Practice for Writing If Statements
EXPLANATION