为什么如果任何(var0) == any(var1)不起作用?



我对编程很陌生,对Python更陌生,我很难弄清楚这一点。我正在尝试制作一个简单的文本hangman游戏,并尝试验证player1的输入。这是我迄今为止所拥有的。

a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
d = list(d)
print(d)
if any(int) == any(d):
print("Invalid input. Please choose a non-number with no spaces or special characters.")

我不明白为什么,无论我的响应中是否包含一个数字,它总是满足我的any(int(==any(d(条件。我知道我一定只是误解了any((的工作原理。

您是对的:问题在于如何使用any()函数。any()返回TrueFalse,这取决于其可迭代参数中的任何元素是否为True,换句话说,如果它们存在并且不是False或空列表或空字符串或0。对于int,这将始终计算为True,因为int确实包含一个True元素,而对于d,也会发生同样的情况,除非在input()函数提示时您没有提供任何输入(您在不键入任何内容的情况下点击return(。你的条件基本上是问以下问题:

if True==True

要解决此问题,只需将代码更改为以下内容:

a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
print(d)
for letter in d:
if letter in int:
print("Invalid input. Please choose a non-number with no spaces or special characters.")
break

然而,最简单的解决方案根本不涉及int列表。事实上,python中有一种特殊的方法可以衡量字符串中是否有数字(或特殊字符(,而这种方法.isalpha()可以用来进一步简化这个过程。以下是如何实现此解决方案:

while True:
d = input("Please choose any word by typing it here: n")
print(d)
if not d.isalpha():
print("Invalid input. Please choose a non-number with no spaces or special characters.")

试试这个:

a = 0
ints = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
word = input()
word_list = list(word)
if any(letter in ints for letter in word_list):
print("Invalid input. Please choose a non-number with no spaces or special characters.")

相关内容

最新更新