python函数与异常处理

一、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")#无论异常与否都会执行

 

转载于:https://www.cnblogs.com/cybg/p/11626981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值