#!/usr/bin/python
#filename:test12.py
while True :
try :
x = int ( input ("please enter a number:"))
break
except ValueError :
print ("Oops! That was no valid number. Try again...")
import sys
try :
f = open ("myfile.txt")
s = f.readline()
i = int(s.strip())
except OSError as err :
print ("OS error: {0}".format(err))
except ValueError :
print ("Could not convert data to a integer.")
except :
print ("Unexcepted error:",sys.exc_info()[0])
raise
print (sys.argv[1:])
for arg in sys.argv[1:]:
try:
f = open (arg,'r')
except IOError:
print('cannot open',arg)
else:
print(arg,'has',len(f.readlines()),'lines')
f.close()
def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as err:
print ("handling run-time error:",err)
try:
raise NameError('HiThere')
except NameError:
print ("An exception flew by!")
raise
class MyError(Exception):
def __init__(self,value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as e:
print ("My exception occurred ,value:",e.value)
f.close()
#!/usr/bin/python
#filename:test12_2.py
def divide(x,y) :
try:
result = x / y
except ZeroDivisionError:
print ("division by zero !")
else:
print ("result is",result)
finally:
print ("executing finally clause")
divide(2,1) #success
divide(2,0) #exception
#divide("2","1") #uncaught error
for line in open("myfile.txt"):
print (line,end="")
with open("myfile.txt") as f :
for line in f:
print (line,end="")
#!/usr/bin/python
#filename: test12_3.py
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print ("After local assignment:",spam)
do_nonlocal()
print ("After nonlocal assignment:",spam)
do_global()
print ("After global assignment:",spam)
scope_test()
print ("In global scope:",spam)
class MyClass:
i = 12345
def f(self):
return "hello world"
x = MyClass()
print (x.i)
print (x.f())
xf = x.f
#while True:
#print (xf()) #this is a endless loop
class Complex:
def __init__(self,realpart,imagpart):
self.r = realpart
self.i = imagpart
x = Complex(1,2)
print (x.r)
print (x.i)
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print (x.counter)
del x.counter
class Dog:
kind = 'canine'
tricks = []
def __init__(self,name):
self.name = name
self.tricks1 = []
def add_trick(self,trick):
self.tricks.append(trick)
self.tricks1.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
print (d.kind)
print (e.kind)
print (d.name)
print (e.name)
d.add_trick("roll over")
e.add_trick("play dead")
print(d.tricks)
print(e.tricks)
print(d.tricks1)
print(e.tricks1)