-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26_variable_scope.py
More file actions
66 lines (55 loc) · 2.52 KB
/
Copy path26_variable_scope.py
File metadata and controls
66 lines (55 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#======================================================================================
# Variable Scope
#--------------------------------------------------------------------------------------
# Variable scope tells us where a variable is visible and available in the code
#======================================================================================
#--------------------------------------------------------------------------------------
# Parameter
#--------------------------------------------------------------------------------------
# A parameter is a variable in a function definition that receives a value when
# the function is called
#--------------------------------------------------------------------------------------
def greet(text): # parameter
print(text)
greet('Hello world')
#--------------------------------------------------------------------------------------
# Local Variable
#--------------------------------------------------------------------------------------
# A local variable is created inside a function and can only be used inside that function
#--------------------------------------------------------------------------------------
def greet():
message = 'Hello Good Morning!' # local variable
print(message)
greet()
#print(message) # local variable cannot be accessed outside the function
#--------------------------------------------------------------------------------------
# Global Variable
#--------------------------------------------------------------------------------------
# A global variable is created outside the functions and can be accessed from anywhere in
# the program
#--------------------------------------------------------------------------------------
name = "Bob Smith" # global variable
def greet():
print(name) # global variable
greet()
print(name)
# Visual understanding
x = 100 # global variable
def display(name): # parameter
age = 25 # local variable
print(name)
print(age)
print(x)
display("Frank")
# x --> Global variable (accessible throughout the program)
# name --> Parameter (accessible only inside display() function)
# age --> Local variable (accessible only inside display() function)
# Another example
case_rule = 'lower' # global variable
def clean_name(name): # parameter
cleaned = name.strip() # local variable
if case_rule == 'lower':
cleaned = cleaned.lower() # local variable
print(f'Cleaned: {cleaned}')
clean_name(' BOb')
print(f'The rule is {case_rule}')