gpt4 book ai didi

python - 使用 string.isalpha 在 python 中评估需求,始终返回 True

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:08 24 4
gpt4 key购买 nike

我试图在 Python3 中定义一个函数来评估输入是否满足给定的要求;它们是:长度必须在 3 到 20 个字符之间(含),必须只有字母和撇号以及“-”和空格。

def validateFirstname(firstname):
#Local Variable
hasFirstname = False
Caracterslist = "/'/-"

if (len(firstname) >= 3 and len(firstname) <= 20 and
firstname.isalpha(), firstname.isspace(), (firstname in Caracterslist)):
hasFirstname = True
return hasFirstname

firstname = str(input("Enter your first name: "))
if (validateFirstname(firstname)):
print("Your first name is: ", firstname)
else:
print("The first name you entered ", firstname, "is not valid!")

实际上,即使名字超过 20 个字符并且包含数字,它也会返回 True……

我不明白为什么...

最佳答案

在你的表达中:

if (len(firstname) >= 3 and len(firstname) <= 20 and
firstname.isalpha(), firstname.isspace(), (firstname in Caracterslist)):

以下部分被评估为元组(注意逗号):

(len(firstname) >= 3 and len(firstname) <= 20 and
firstname.isalpha(), firstname.isspace(), (firstname in Caracterslist))

这基本上是以下形式:

(a and b and c, f, g, h)

因此被评估为一个元组。

这个元组,无论其内容如何,​​都将评估为 True,例如:

>>> if (False,False,False):
print "Was True"

Was True

发生这种情况是因为 tuple 本身被认为是 True/False 意义。

在 Python 中,以下值被认为是假的 Python Documentation :

  1. None

  2. False

  3. zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  4. any empty sequence, for example, '', (), [].

  5. any empty mapping, for example, {}.

  6. instances of user-defined classes, if the class defines anonzero() or len() method, when that method returns the integer zero or bool value False. 1

All other values are considered true — so objects of many types are always true.

由于元组为空(,) 它将被视为True,因此表达式的计算结果为True。您需要用适当的 boolean 运算符替换 ,。这将停止将表达式视为元组,因为它将采用 (a)

形式

您的表达式存在逻辑问题,您需要为您的逻辑计算出正确的条件链。但是,您还必须解决元组创建问题(如上)。适当的逻辑可能是:

#if fistname is not all spaces, and is of correct length, and (is either all alphabetical or contains a character in characterlist)
if not firstname.isspace() and 3 <= len(firstname) <= 20 and (firstname.isalpha() or any(c in firstname for c in Caracterslist)):
return firstname

关于python - 使用 string.isalpha 在 python 中评估需求,始终返回 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20157390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com