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

猜你喜欢

转载自www.cnblogs.com/cybg/p/11626981.html