Python Examples

x = "global"

def foo():
 print("x inside :", x)

foo()
print("x outside:", x)
##############
x = "global"

def foo():
 x = x * 2
 print(x)
foo()
#############
def foo():
 y = "local"

foo()
print(y)

###############
def foo():
 y = "local"
 print(y)

foo()

#################
x = "global"

def foo():
 global x
 y = "local"
 x = x * 2
 print(x)
 print(y)
 
foo()


##################
x = 5

def foo():
 x = 10
 print("local x:", x)

foo()
print("global x:", x)

################## NON LOCAL

def outer():
 x = "local"
 
 def inner():
 nonlocal x
 x = "nonlocal"
 print("inner:", x)
 
 inner()
 print("outer:", x)

outer()


######### call by reference ###########
def ref_demo(x):
 print "x=",x," id=",id(x)
 x=42
 print "x=",x," id=",id(x)

x = 9
id(x)
ref_demo(x)
id(x)

#####
def func1(list):
 print list
 list = [47,11]
 print list

fib = [0,1,1,2,3,5,8]

func1(fib)

print fib

#####
def func2(list):
 print list
 list += [47,11]
 print list

fib = [0,1,1,2,3,5,8]

######### how to prevent ######
func2(fib[:])



##########
def printInfo(name, age, rollno ):
 print ( "Name =", name )
 print ( "Age =", age )
 print ( "rollno =", rollno )



printInfo("Ashish",18,12002)

printInfo(18,12002, "Ashish")

printInfo(age=18,rollno=12002, name="Ashish")

######

def printInfo(name="NO NAME", age=18, rollno=12002 ):
 print ( "Name =", name )
 print ( "Age =", age )
 print ( "rollno =", rollno )



#############
#Variable argument lengths by position
def fn(*foo): 
 for i in foo: 
 print i

fn(1,2,3,4,5,6,7)
##Variable argument lengths by keyword
def fn(**foo):
 for i in foo.keys():
 print i,":",foo[i]
fn(name="John",age="50")

############

class Students :
 def __init__(self, name,rollno):
 self.name=name
 self.rollno = rollno
 def display(self):
 print ("My name is "+ self.name + " and my Roll number is "+ self.rollno)

class Car(object):
 """
 blueprint for car
 """

 def __init__(self, model, color, company, speed_limit):
 self.color = color
 self.company = company
 self.speed_limit = speed_limit
 self.model = model

 def start(self):
 print("started")

 def stop(self):
 print("stopped")

 def accelarate(self):
 print("accelarating...")

 def change_gear(self, gear_type):
 print("gear changed")

 def display(self):
 print (self.color)
 print (self.company)
 print (self.model)
 print (self.speed_limit)

class shape:
 def foo():
 print ("I am the patent class")

class Rectange(shape):
 def __init__(self, length, breadth, unit_cost=0):
 self.length = length
 self.breadth = breadth
 self.unit_cost = unit_cost
 
 def get_perimeter(self):
 return 2 * (self.length + self.breadth)
 
 def get_area(self):
 return self.length * self.breadth
 
 def calculate_cost(self):
 area = self.get_area()
 return area * self.cost
# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s ", %(r.calculate_cost()))


class shape:
 def foo(self):
 print ("I am the patent class")

class Rectangle(shape):
 def __init__(self, length, breadth, unit_cost=0):
 self.length = length
 self.breadth = breadth
 self.unit_cost = unit_cost

 def foo(self):
 print ("I am the child class")
 def get_perimeter(self):
 return 2 * (self.length + self.breadth)

 def get_area(self):
 return self.length * self.breadth

 def calculate_cost(self):
 area = self.get_area()
 return area * self.unit_cost
# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s " %(r.calculate_cost()))
print (r.foo())

###################################################
def fetcher( obj, index):
 return obj[index]

a=[1,2,3,4,5]
try:
 fetcher(a,5)
except IndexError as e:
 print ("What happened ?", e)



def fetcher( obj, index):
 return obj[index]

a=[1,2,3,4,5]
try:
 fetcher(5)
except IndexError as e:
 print ("What happened ?", e)




def fetcher( obj, index):
 return obj[index]

a=[1,2,3,4,5]
try:
 fetcher(5)
except IndexError as e:
 print ("What happened ?", e)
except Exception as e:
 print ("INSIDE EXCPEITION - What happened ?", e)





a=[1,2,3,4,5]
try:
 fetcher(a,4)
 raise IOError
except IndexError as e:
 print ("What happened ?", e)
except Exception as e:
 print ("INSIDE EXCPEITION - What happened ?", e)



class Bad(Exception):
 def __init__(self):
 self.message="Bad Exception is caught"
 pass

try:
 raise Bad
except Bad as e:
 print ("Raised bad", e.message)