实验12 异常、递归
实验内容:
1. 编写一个函数,提示输入两个数字a,b,并进行a与b的除法运算,把运算结果打印出来。要求对输入和程序进行检测,可以排除所有的错误。(要求,可以使用以下的异常检查下面的错误:IOError、ValueError、ZeroDivisionError等,不能使用BaseException)
def division(a,b): try:
result=float(a)/float(b) except ZeroDivisionError:
print \"Error:The divisor can not be zero\" else:
return result
def main(): try:
a,b=input(\"Enter two numbers to finish the division:\") except IOError:
print \"Error:Wrong input or output\" except ValueError:
print \"Error:Wrong value\" except SyntaxError:
print \"Error:No symbols or whitespaces\" except TypeError:
print \"Error:The number of integer U input is not enough\" except NameError:
print \"Error:No characters or strings\" else:
print division(a,b)
main()
2. 编写一个函数以读的方式打开一个文件,如果文件路径不对,重新输入,直到输入成功。 def FileOpen(name): t=[] try:
f=open(name,\"r\") t=f.readlines() print t finally:
f.close()
def main(): while True: try:
name=raw_input(\"Enter a filename with its location:\") FileOpen(name)
except BaseException:
print \"Error,try again.\" else:
return None break
main()
3.编写一个递归函数,实现某数的阶乘Fact
def Fact(n): if n==0: return 1 if n>0:
return n*Fact(n-1)
def main():
n=input(\"Enter a number to finish the factorial function:\") print Fact(n)
main()
4.编写一个递归函数,实现Fabonacci数列
def Fib(n):
if n==1 or n==2: return 1 else:
return Fib(n-2)+Fib(n-1)
def main():
n=input(\"Enter a number to finish the fibonacci function:\") print Fib(n)
main()
5.编写一个递归函数,实现字符串反序。 def revchar(str): if len(str)==1: return str[0:] else:
return revchar(str[1:])+str[0]
def main():
str=raw_input(\"Enter a string:\") print revchar(str)
main()
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- huatuoyibo.net 版权所有 湘ICP备2023021910号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务