Scope is the region in a program where a variable operates.
Variable created outside a function is available outside and inside all functions. It is called a global variable.
Variable created inside a function is available inside that function. The variable is called local in scope.
Variable created inside a function within a function is available to both functions.
The same variable assigned inside and outside has local scope in function.
If you want a variable inside a function to be available everywhere (globally) then you must label it as global.
#SCOPE
#Variable assigned outside a function has global scope
#Variable assigned inside a function has local scope
#Variable created inside a function within a function is available to both functions.
#The same variable assigned inside and outside has local scope in function
#A variable declared global within a function is global
myint = 5 #Global scope
def sumfunct():
return myint * 2
print(sumfunct()) #Output is 10
def sumfunct():
myint = 4 #Local scope
return myint
print(sumfunct()) #Output is 4
myint = 5
def sumfunct():
myint = 9 #Local scope for myint
return myint * 2
print(sumfunct()) #sumfunct is 18
def sumfunct():
x = 20
def funcinfunc():
print (x) #x=20
return funcinfunc()
sumfunct() #Call sumfunct() and print 20 from funcinfunc()
myint = 5 #Global scope
def sumfunct():
myint = 8
return myint #myint = 8
print(sumfunct()) #Output is 8
def sumfunct():
global x
x = 6
return x
sumfunct()
print (x) #Output is 6
Table of Contents
Ch1-Starting Out
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Variable Scope
Ch6-Bubble Sort
Ch7-Intro to OOP
Ch8-Inheritance
Ch9-Plotting
Ch10-Files
Ch11-Print Format
Ch12-Dict-Zip-Comp
Ch13-Slice Arrays