Advertisement
# Python - Local variables
# Defining the function show_values()
def show_values():
# Declaring and initializing local variables of the function
year = 2019
message = 'Have a good day!'
time = '17:09'
print('year : ', year)
print('message : ', message)
print('time : ', time)
# Calling the show_values() function
show_values()
year : 2019
message : Have a good day!
time : 17:09
# Python - Trying to access a local variable outside its scope
# Defining the function show_message()
def show_message():
# Declaring and initializing local variables of the function
message = 'Have a good life!'
# Printing value of a local variable within its function
print('message : ', message)
# Calling the show_message() function
show_message()
# Trying to access a local variable from the outside its scope/function
print('message : ', message)
message : Have a good life!
time : 17:09
Traceback (most recent call last):
File "D:/Python Programs/local2.py", line 20, in
print('message : ', message)
NameError: name 'message' is not defined
Advertisement
# Python - Trying to change values of global variables
fruit = 'Apple'
quantity = 2
price = 10.99
# Declaring local variables with the same name as global variables in a function,
# overshadows global variables but does not impact the original values of global variables.
def mango_info():
fruit = 'Mango'
quanity = 5
price = 15.99
print('Printing the values of local variables :')
print('fruit : ', fruit)
print('quantity : ', quantity)
print('price : ', price)
# Calling the fruit_info() function
mango_info()
print('Printing the values of global variables :')
print('fruit : ', fruit)
print('quantity : ', quantity)
print('price : ', price)
Printing the values of local variables :
fruit : Mango
quantity : 2
price : 15.99
Printing the values of global variables :
fruit : Apple
quantity : 2
price : 10.99
# Python - Passing values of local variables
def add(x,y):
result = x + y
return result
def subtract(x,y):
result = x - y
return result
def multiply(x,y):
result = x * y
return result
def do_math():
a = 10
b = 25.5
sum = add(a,b)
print('sum : ', sum)
sum = subtract(a,b)
print('difference : ', sum)
sum = multiply(a,b)
print('multiplication : ', sum)
# Calling a function func()
do_math()
sum : 35.5
difference : -15.5
multiplication : 255.0
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement