复习:
1、python异常处理机制
try:
a=int(input('a='))
b=int(input('b='))
c=a/b
print(c)
except ZeroDivisionError:
print('除数不能为0')
except ValueError:
print('输入应该为整数')
finally:
print('计算结束')
try:
a=int(input('a='))
b=int(input('b='))
c=a/b
except BaseException:
print('出错了')
else:
print(c)
import traceback
try:
print(1/0)
except:
traceback.print_exc()
2、类和对象
class Student:
native_place='山东'
def __init__(self,name,age):
self.name=name
self.age =age
def eat(self):
print('eating')
@staticmethod
def method():
print('静态方法')
@classmethod
def cm(cls):
print('类方法')
print(Student.native_place)
stu1=Student('柠柠',3)
Student.eat(stu1)
stu1.eat()
Student.method()
Student.cm()
3、函数
两数相加
def ADD(a,b):
c=a+b
return c
res1=ADD(3,5)
print(res1)
res2=ADD(a=5,b=78)
print(res2)
对数字另赋值,列表增加
def fun(arg1,arg2):
print('arg1',arg1)
print('arg2', arg2)
arg1=100
arg2.append(10)
print('arg1', arg1)
print('arg2', arg2)
fun(12,[3,4,6,7,8,8])
fun(arg1=12,arg2=[3,4,6,7,8,8])
分开列表中的奇偶
def fun(num):
odd=[]
even=[]
for i in num:
if i%2:
odd.append(i)
else:
even.append(i)
return odd,even
print(fun([1,34,57,78,79,6,45]))
计算数乘
def fac(n):
if n==0:
return 1
elif n==1:
return 1
else:
return n*fac(n-1)
print(fac(7))
计算斐波那契数列
def fib(n):
if n==1:
return 1
elif n==2:
return 1
else:
return fib(n-2)+fib(n-1)
print(fib(4))
函数不同参数类型
def fun1(arg):
print(arg)
def fun2(*arg):
print(arg)
def fun3(**arg):
print(arg)
list=[1,2,3]
dict1={'a':1,'b':2,'c':3}
dict2=dict(a=1,b=2,c=3)
fun1(1)
fun2(1,2,3)
fun2(*list)
fun3(a=1,b=2,c=3)
fun3(**dict1)
fun3(**dict2)