首页 > 编程语言 > 详细

python函数与异常处理

时间:2019-10-06 13:44:34      阅读:113      评论:0      收藏:0      [点我收藏+]

一、python函数

  1.函数自定义格式:

  分为有无返回值两种类型

def 函数名():
    代码语句
    --------
    --------

  return 参数1,(参数2等)------------------用逗号隔开即可

  1.1举例:

# def hcf(x, y):
#    #该函数返回两个数的最大公约数
 
#    # 获取最小值
#    if x > y:
#        smaller = y
#    else:
#        smaller = x
 
#    for i in range(1,smaller + 1):
#        if((x % i == 0) and (y % i == 0)):
#            vans = i
 
#    return vans
 
 
# # 用户输入两个数字
# while 1:
#     num1 = int(input("输入第一个数字: "))
#     num2 = int(input("输入第二个数字: "))
     
#     print( num1,"和", num2,"的最大公约数为", hcf(num1, num2))
#     print( num1,"和", num2,"的最小公约数为",int(num1*num2/hcf(num1, num2)))

  这里用到的即是带返回值的情况。

二、异常处理:

score=input("")
try:#尝试执行正常语句,有异常则在except处显示
    score=eval(score)
    if 0<=score<=100:
        print(score,is right.)
    elif score not in range(0,100):
        print(score,is not specific range!)
    else:
        raise NameError#判断是否为数字
except NameError as err:
    print(err,is not Number!)
else:
    print("success!")
finally:
    print("done")#无论异常与否都会执行

 

python函数与异常处理

原文:https://www.cnblogs.com/cybg/p/11626981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!