Presentation is loading. Please wait.

Presentation is loading. Please wait.

Scope of Variables. A variable can have something called a ‘scope’. This refers to its accessibility. Scope of Variable Mr.Skelton …Dalriada School Scope.

Similar presentations


Presentation on theme: "Scope of Variables. A variable can have something called a ‘scope’. This refers to its accessibility. Scope of Variable Mr.Skelton …Dalriada School Scope."— Presentation transcript:

1 Scope of Variables

2 A variable can have something called a ‘scope’. This refers to its accessibility. Scope of Variable Mr.Skelton …Dalriada School Scope of Variable Mr.Gamble …G4 Scope of Variable President Obama …The Whitehouse!

3 A variable can be declared in one of two ways… When it is accessible from all parts of a program (ie. Anywhere!) A GLOBAL Variable. When it is accessible ONLY within a function/procedure. A LOCAL Variable.

4 Look at the following PYTHON program: name = ‘Mary Poppins’ print(name) So far, we have been working with variables in this manner. Note that I can call the variable name from ANYWHERE in the program…i.e. it is accessible from anywhere! These declarations have usually been done at the start of our programs, and have been declared OUTSIDE of any functions. These are referred to as GLOBAL variables.

5 Look at the following PYTHON program: def Greeting(): name = 'Mary Poppins' age = 200 address = 'Far Far away' Notice that these variables have been declared inside a function. This means, the variables are only accessible from within the fucntion. Hence, we have declared LOCAL variables here. If I typed print(name) outside of this function, it would result in a compile error!

6 So far, we have learnt some important facts about GOOD programming… 1.Use meaningful identifiers for Variable names: e.g. Name and not x 2.Use commenting to aid understanding: e.g. #this function checks to see if a letter is in the phrase Best programming practice avoids use of global variables and in favour of local variables. 3.Avoid use of global variables in favour of local variables.

7

8 Result ? 36 NameError: name 'fixed_number' is not defined

9 Look carefully at this code… This simply asks the user for a number and then calls a function to increment each time the CheckGuess function is called. Type this into Python & see what happens

10 Look carefully at this code… Note the use of the keyword global. This allows functio to modify/change the value of the global variable guesses! Insert global guesses

11 Task You are expected to use Functions in your solution


Download ppt "Scope of Variables. A variable can have something called a ‘scope’. This refers to its accessibility. Scope of Variable Mr.Skelton …Dalriada School Scope."

Similar presentations


Ads by Google