http://www.yuyong.net

技术编辑教你解决python3中怎么减少try语句的使用

电脑现已成为我们工作、生活和娱乐必不可少的工具了,在使用电脑的过程中,可能会遇到python3中怎么减少try语句的使用的问题,如果我们遇到了python3中怎么减少try语句的使用的情况...

电脑现已成为我们工作、生活和娱乐必不可少的工具了,在使用电脑的过程中,可能会遇到python3中怎么减少try语句的使用的问题,如果我们遇到了python3中怎么减少try语句的使用的情况,该怎么处理怎么才能解决python3中怎么减少try语句的使用带来的困扰呢,对于这样的问题其实我们只需要python3这里以JUPYTER NOTEBOOK作为示范。新建一个PY文档。try:integer = int(input("Please input an integer."))print("The integer is %d" %integer)except:print("You are not inputing an integer.")如果我们要判断用户输入的是整型还是其它数据,可以用这样就解决了这样的问题,接下来给大家带来python3中怎么减少try语句的使用的详细操作步骤。

工具/原料

python3

方法/步骤

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

技术编辑教你解决python3中怎么减少try语句的使用

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语句的使用

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语句的使用

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语句的使用

zero = 0

try:

"100"[-1] == 0

print("The last number is zero.")

except:

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

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

技术编辑教你解决python3中怎么减少try语句的使用

if 100 % 10 == 0:

print("The last number is zero.")

else:

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

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

技术编辑教你解决python3中怎么减少try语句的使用

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

try:

dict["a"] == 1

print(True)

except:

print(False)

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

技术编辑教你解决python3中怎么减少try语句的使用

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

def check(x):

if dict.get(x) == 1:

return True

else:

return False

check("a")

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

技术编辑教你解决python3中怎么减少try语句的使用

注意事项

利用PYTHON3里面的一些其他函数即可解决问题

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。