Objectives

Students will be able to:

  • understand that a function definition/signature can include parameters
  • understand that when calling a function, the call must match the parameter list.

Global Variable Solution

def calculateTax():

if salary>20000:

tax = salary * 0.25

if salary>10000:

tax = salary * 0.125

else:

tax = 0

print(f"Salary:${salary} ; Tax: ${tax}")

def main():

global salary

numStaff = int(input("How many staff will you process: "))

for i in range(numStaff):

salary = int(input("Enter a salary: "))

calculateTax()

#program calling the function

main()

Parameter Solution

def calculateTax(salaryData):

if salaryData>20000:

tax = salaryData * 0.25

if salaryData>10000:

tax = salaryData * 0.125

else:

tax = 0

print(f"Salary:${salaryData} ; Tax: ${tax}")

def main():

numSalary = int(input("How many salaries will you enter: "))

for i in range(numSalary):

salary = int(input("Enter a salary: "))

calculateTax(salary) #call a function and give it some data to process

#call main

main()

Intro to parameters

functions sharing data

 

Intro to Parameters

Parameters allow functions to share data.

We can define and function to process parameters eg:

#this function adds two numbers and displays the result

public static void addTwo(int num1, int num2):

int total = num1 + num2;

System.out.println("Total: "+total);

}

Then, when needed, we can call the function:

public static void main(String[] args){

addTwo(7,2)

addTwo(0,-2)

addTwo(13,4)

}

Getting started

Copy the starter code into your IDE and complete the worksheet.

Review

Parameters allow functions to share data. They do this by using parameters.

When Function A passes data to Function B, Function B uses its parameters to grab the data and then it can process the data!

This strategy reduces the need for global variables.

Helper Video

To reduce the need for global variables we are going attempt to rewrite the program.

We will design functions that process data.

Parameters help functions pass data to each other.

Let's see how it works. Follow the video and then complete the extension activity.

Tags

module function return identifier parameter pseudocode return typedefinecalldata type