python3中怎么减少try语句的使用

2025-11-19 11:11:13

1、这里以JUPYTER NOTEBOOK作为示范。新建一个PY文档。

python3中怎么减少try语句的使用

2、try:

    integer = int(input("Please input an integer."))

    print("The integer is %d" %integer)

except:

    print("You are not inputing an integer.")

如果我们要判断用户输入的是整型还是其它数据,可以用try和except。

python3中怎么减少try语句的使用

3、integer = int(input("Please input an integer."))

if isinstance(integer, int) is True:

    print("The integer is %d" %integer)

else:

    print("You are not inputing an integer."光岔)

我们可以用if和else来进行代替。

python3中怎么减少try语句的使用

4、integer = int(input("Please input an integer."))

if isinstance(integer, int):

    print("The integer is %d" %integer)

else:

    print("You are not inputing an integer.")

也可以简化一下书写。

python3中怎么减少try语句的使用

5、zero = 0

try:

    "100"[-1] == 0

    print("The last number is zero.")

except:

 爬拒泰脾争   print("The last number is not zero.")

    

如果我们面对一些要判断两个对应的值是否相同,会经常用try。

python3中怎么减少try语句的使用

6、if 100 % 10 == 0:

    print("The last number is zero.")

else:

    print("The last number is not zero.")

    

这个时候其实我们就可以用算术的方法去判断是否结尾为0,不需要用到try。

python3中怎么减少try语句的使用

7、dict = {"a": 1, "b": 4, "c": 9}

try:

    dict["a"] == 1

    print(True)

except:

    print(False)

    

如果有字典我们要判断数据用try一个一个来就太慢了。

python3中怎么减少try语句的使用

8、dict = {"a": 1, "b": 4, "c": 9}

def check(x):

    if dict.get(x) == 1:

        return True

    else:

        return False

        

check("a")

通过定义函数就可以大大缩小代码量。

python3中怎么减少try语句的使用

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢