Lecture 3
Lecture 3
Sherina Sally
OUTLINE
• Introduction to variables
• Variable assignment
All Rights Reserved
• Dynamic typing
• Naming conventions
• Variable scope
1
VARIABLES
• Python variables are named entities to store data
x = 10
• Created at the moment when a value is assigned
x = ‘ Joe’ x = “ Joe”
• Dynamically typed
NAMING CONVENTIONS
• Start with a letter or the underscore( _ ) character
• Variable names can only contain letters, numbers and underscores (A-z, 0-9, and _ )
2
MULTIPLE VARIABLE ASSIGNMENT
• Global Scope
3
SCOPES OF VARIABLES …(2)
• Enclosing scope
- Applies in nested functions
• Built-in Scope
def outer():
x = “outer x”
All Rights Reserved
def inner():
x = “inner x”
print(x)
inner()
x = max(4,5,3,…..)
print(x)
outer()
print(x)
4
global
• Enforce a variable to behave in the global scope
def inner():
global x
x = “inner x”
inner()
print(x)
nonlocal
• In nested functions, variables in the outer function cannot be changed in the inner function
• Enables to change the values of the variables in the outer function from the inner function
All Rights Reserved
def outer():
x=5
def inner():
nonlocal x
x=x+3
print(x)
inner()
outer()
Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 10
5
Department of ICT, Faculty of Technology, University of Colombo