try except else

一直对try…except有畏惧,并且懒得写,只想自己调试。后来觉得还是应该写,defensive的编程方式。cs50上这个例子特别合适,记下来:

  1. 用while True自动循环,输入错误就再循环,正确就退出。
  2. 在try except else语句中,只写有可能出错的语句,越少行数越好。print这种不会出错的句子不要写在一起。
while True:
    try:
        x = int(input("What's x? "))
    except ValueError:
        print("x is not an integer")
    else:
        break
        
print(f"x is {x}")

1. 分拆函数的写法

def main():
    x = get_int()
    print(f"x is {x}")

def get_int():
    while True:
        try:
            x = int(input("What's x? "))
        except ValueError:
            print("x is not an integer")
        else:
           # return x
            break
    return x

main()

2. 分拆函数的更紧凑写法
利用return特性,return不仅仅返回数值,也能跳出循环,有break的作用

def main():
    x = get_int()
    print(f"x is {x}")

def get_int():
    while True:
        try:
            x = int(input("What's x? "))
        except ValueError:
            print("x is not an integer")
        else:
           return x

main()

3. 更更紧凑写法
如果int(input("What's x? ")) 没有语法错误,则直接返回;有语法错误,就跳到except。跟写法2都行,但是我觉得写法2更加容易阅读。

def main():
    x = get_int()
    print(f"x is {x}")

def get_int():
    while True:
        try:
            return int(input("What's x? "))
        except ValueError:
            print("x is not an integer")

main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值