The Advantages of Function
The Advantages of Function
def calcAreaPeri(Length,Breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
#a tuple is returned consisting of 2 values area and perimeter
return (area,perimeter)
l = float(input("Enter length of the rectangle: "))
b = float(input("Enter breadth of the rectangle: "))
#value of tuples assigned in order they are returned
area,perimeter = calcAreaPeri(l,b)
print("Area is:",area,"\nPerimeter is:",perimeter)
def trafficLight():
signal = input("Enter the colour of the traffic light: ")
if (signal not in ("RED","YELLOW","GREEN")):
print("Please enter a valid Traffic Light colour in
CAPITALS")
else:
value = light(signal)
if (value == 0):
print("STOP, Your Life is Precious.")
elif (value == 1):
print ("PLEASE GO SLOW.")
else:
print("GO!,Thank you for being patient.")
#function ends here
def light(colour):
if (colour == "RED"):
return(0);
elif (colour == "YELLOW"):
return (1)
else:
return(2)
trafficLight()
print("SPEED THRILLS BUT KILLS")
Scope of a Variable
A variable defined inside a function cannot be accessed outside it. Every variable has a well-defined accessibility. The
part of the program where a variable is accessible can be defined as the scope of that variable. A variable can have one
of the following two scopes: A variable that has global scope is known as a global variable and a variable that has a
local scope is known as a local variable.
(A) Global Variable In Python, a variable that is defined outside any function or any block is known as a global variable.
It can be accessed in any functions defined onwards. Any changemade to the global variable will impact all the
functions in the program where that variable can be accessed.
(B) Local Variable A variable that is defined inside any function or a block is known as a local variable. It can be
accessed only in the function or a block where it is defined. It exists only
till the function executes
#Add tax to the total cost to calculate net amount payable by the
#customer
tax = 0.18 * total_cost;
net_price = total_cost + tax
print("Net amount payable = ",net_price)
#function header
def sumSquares(n): #n is the parameter
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is: ",sum)