gpt4 book ai didi

python - 为什么 While 循环返回一个变量而不返回另一个变量?

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:28 27 4
gpt4 key购买 nike

我正在尝试自学 Python 并正在为自己构建一个基本的刽子手游戏。我有一点办法,但现在我被卡住了。

我尝试将大部分用于猜测的“计数器”放入一个函数中,然后引用另一个函数来实际计算出猜测是否正确。

所以这是我的计数器函数:

def game(generated_word):
hangman_lst = []
guess_num = 0
for i in range(0, len(generated_word)):
hangman_lst.append("__")
print(" ".join(hangman_lst))

while "__" in hangman_lst:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
guess(l, random_word_stripped, hangman_lst, guess_num)
elif guess_num == 9:
print("Sorry - you lose!")
print("The word was " + str(random_word_stripped))
break
else:
l = input("This is guess #" + str(guess_num + 1) + ":")
guess(l, random_word_stripped, hangman_lst, guess_num)

if "__" not in hangman_lst:
print("**Ta-da!** You're a winner!")

这是我用来判断猜测是否正确的函数:

def guess(ltr, word, lst, try_num):
upper_ltr = ltr.upper()
if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
elif len(upper_ltr) < 1:
print("You didn't enter a letter, try again:")
print(" ".join(lst))
elif upper_ltr in lst:
print("You already guessed that letter, try again:")
print(" ".join(lst))
elif upper_ltr not in word:
print("Sorry, that's incorrect. Try again.")
print(" ".join(lst))
try_num += 1
return try_num
else:
for n in range(0, len(word)):
if word[n] == upper_ltr:
lst[n] = upper_ltr
print("Nice job. That's one. You get a bonus guess.")
print(" ".join(lst))
return lst

所以它有点起作用,因为 hangman 单词会根据猜测的字母更新。但我无法让计数器工作 - guess_num 似乎总是保持在 0,所以它总是循环遍历这部分:

if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
guess(l, random_word_stripped, hangman_lst, guess_num)

但是,guess 函数似乎返回了 lst,那么为什么 try_num 没有返回呢?

干杯!

最佳答案

您需要增加 guess_num。在 while 循环的末尾添加 guess_num = guess_num + 1 可以解决这个问题,但您只希望 guess_num 在猜错时递增,因此您可以这样做。 (我还没有测试过这个)

while "__" in hangman_lst:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
if guess(l, random_word_stripped, hangman_lst, guess_num):
print("good guess")
else:
guess_num += 1
elif guess_num == 9:
print("Sorry - you lose!")
print("The word was " + str(random_word_stripped))
break
else:
l = input("This is guess #" + str(guess_num + 1) + ":")
if guess(l, random_word_stripped, hangman_lst, guess_num):
print("good guess")
else:
guess_num += 1

然后在您的猜测函数中,您需要添加行 return Truereturn False 以根据猜测是否有效返回适当的 True/False 值。

所以猜测函数的一部分

if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))

需要改成

if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
return False

然后您将为每个 if 条件执行此操作。一旦 python 看到 return 语句,它就会退出该函数,并返回您告诉它返回的任何内容,在我们的例子中,这将是 True 或 False。

关于python - 为什么 While 循环返回一个变量而不返回另一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37150345/

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