Objectives

Students will be able to:

  • understand that different functions need access to the same variables
  • understand that variables declared inside a function (local variables) are not available to other functions
  • understand that global variables are available to all functions in a program

Variable Scope

global vs local

 

Global vs Local

A computer program is being written.

There will be some functions.

There will be some variables.

A local variable can only be used by the function that creates it.

A global variable can be used by all functions in the program.

Let's take a moment to explore this idea in Python.

Open a new file in your IDE called variableScope

Copy the into your file.

Task 1

Watch the video and complete the Worksheet.

Tax Calculator I

An accountant is creating a handy tax calculator.

The code looks good. She has designed functions to perform specific tasks.

The functions are called when they are needed by the program.

But it doesn't work as expected.

Use your current understanding of variable scope to help fix the problem.

You should not need to design any new functions.

Tax Calculator II

The program does not display the net pay.

Design a new function called displayNetPay().

This function will display the net pay after tax is deducted from the gross pay.

Variable Scope - Review

Take a moment to analyse your solution. If possible, talk about it with a partner.

How much do you feel you understand variable scope in Python?

Tags

module function return identifier parameter pseudocode return typedefinecalldata type