代码是一个简单的猜字游戏,有一个指定的秘密词,用户必须在一定次数的尝试中猜测。如果用户想到寻求帮助,他将得到一个提示。
问题是在第10行和第11行,我的想法是用户不应该为了得到提示而猜出"help“这样的确切单词,但也可以为相同的结果猜测它的同义词。虽然对于这个程序来说,第10行非常好,但是它占用了大量的空间,如果您想要包含更多产生提示的作品,代码就会变得更加混乱。
另一方面,第11行根本不起作用,在想了几分钟之后,我更仔细地查看了or运算符,发现它没有将猜测与第一个单词之后的其他单词进行比较,而是检查布尔值是否为真。因为每个非空字符串都有True值,所以每个单词都会生成提示。
现在的问题是:是否有办法将每个同义词与第10行中的用户猜测进行比较,这就更简洁了。或者是一个内置函数,用于将多个值与我没有看到的另一个值(在本例中是字符串)进行类似的比较。
def guessing_game():
secret_word = "Schinken"
guess = ""
guess_count = 0
guess_limit = 5
print("Guess the secret word, you have " + str(guess_limit) + " tries")
while guess != secret_word and guess_count != guess_limit:
guess = input("Take a guess: ")
guess_count += 1
if guess.lower() == "hint" or guess.lower() == "tipp" or guess.lower() == "hinweis" or guess.lower() == "hilfe" or guess.lower() == "clue" or guess.lower() == "help" or guess.lower() == "advice":
#if guess.lower() == "hint" or "help" or "hinweis" or "hilfe" or "tipp" or "clue" or "advice":
print("Hint: German word for Ham")
elif guess != secret_word and guess_count < guess_limit:
print("Sorry that is wrong, you will have to try again")
if guess == secret_word:
print("Congratulations, you are correct! You Win!")
else:
print("Sorry, you ran out of guesses. You Lose!")发布于 2020-03-03 12:52:48
您可以将选项放在列表中并使用in
if guess.lower() in ["hint", "tipp", "hinweis", "hilfe", "clue", "help", "advice"]:https://stackoverflow.com/questions/60507643
复制相似问题