当第二个条件通常会导致一个错误时,使用“and”是一个好的做法吗

2024-04-26 22:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

像float('.')这样的函数通常会导致ValueError。但是,如果适当地放置条件,就可以避免ValueError异常。这算不算坏习惯?你知道吗

先检查小数点,然后检查数字的示例

a = '1.2'

if a[1] != '.':
   if float(a[1]) != 0:
      print('is a digit and non zero')

使用“and”运算符执行相同操作的示例

a = '1.2'

if a[1] != '.' and float(a[1]) != 0:
   print('is a digit and non zero')

翻转“and”运算符的条件会导致错误

a = '1.2'

if float(a[1]) != 0 and a[1] != '.':
   print('is a digit and non zero')

从技术上讲,第一个和第二个示例是相同的,但是翻转第二个示例的条件会导致错误。所以再说一次,这是不好的做法,我应该用它来保存一行吗?你知道吗


Tags: and函数示例ifis错误运算符float
3条回答

首先,在我看来,它不像是全局逻辑,因为你在检查[1],在这种情况下,只有你得到它“.”但是考虑一个场景a='11.1',那么你会得到一个[1]作为1,它不是“.”并且在你的问题和操作中,它首先检查第一个条件如果这是假的,那么它不会检查第二个条件,但是如果1变成真的在您的情况下,只有它会检查第二个条件a[1]='.',但如果您没有更好的异常处理代码,并且如果您想检查浮点值,则不建议您直接执行 尝试: 浮子(a) 除了值错误: #句柄值错误

如前所述,tryexcept是Python中根据EAFP principle的首选方法。你知道吗

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

因为我假设你的问题是从你实际做的事情中简化出来的,所以我也将链接this answer,它将讨论try: except:计时与检查值存在性(或其他if语句)的比较。你知道吗

作者的主要结论是:

So, whereas an if statement always costs you, it's nearly free to set up a try/except block. But when an Exception actually occurs, the cost is much higher.

Moral:

It's perfectly OK (and "pythonic") to use try/except for flow control, but it makes sense most when Exceptions are actually exceptional.

在大多数情况下,清晰易读是最佳实践。你知道吗

从我所知道的坏习惯可以归结为有多少次别人会问自己“这是怎么回事?”?“或者对结果感到惊讶。你要尽量减少这种情况发生的频率。你知道吗

我建议使用tryexcept块来捕获ValueError,因为您知道这是一个可能的问题。你知道吗

我认为最好做以下几点。我假设你正在接受用户输入。你知道吗

number_entered = input("Enter number: ")

try:
    x = float(number_entered)
except ValueError as e:
    print(f"{x} is not a valid number. Pease enter a valid number.")

相关问题 更多 >