我对python很陌生,我正在从教程中迭代一个小的初学者项目。这是个猜字游戏。我有一个具体的秘密词的提示主列表,我想打印一个提示,在错误的猜测之后,打印下一个提示。
我想要做到这一点,而不使用一堆if语句,因为我认为一定有一个更有效的速记方式。
import random
secret_word_list = ["Duck"]
duck_hint_list = ["Hint: It's a bird", "Hint: it swims", "Hint: It loves to be in a row"]
secretWord = random.choice(secret_word_list)
guess = ""
guess_limit = 3
guess_attempts = 0
game_end = False
while guess != secretWord and guess_attempts != guess_limit:
if secretWord == "Duck":
if guess_attempts != guess_limit:
print(random.choice(duck_hint_list))
guess = (input("Guess the secret word: "))
guess_attempts += 1
if guess_attempts == guess_limit:
print("YOU LOSE IDIOT")
else:
print("You Win!")正如您所看到的,我尝试使用random.choice,但是它明显的缺点是它会打印两次相同的提示。
发布于 2022-07-04 16:19:13
从0的索引开始,并在需要时使用它打印提示。当您打印提示时,请使用1增加索引。
如果您想遍历提示,并可能重复它们,请使用:index % len(duck_hint_list)作为索引。
如果希望提示以随机顺序出现,首先在duck_hint_list上使用duck_hint_list。
发布于 2022-07-04 18:52:08
# import random
secret_word_list = "Duck"
duck_hint_list = ["Hint: It's a bird", "Hint: it swims", "Hint: It loves to be in a row"]
# secretWord = random.choice(secret_word_list)
guess = ""
guess_limit = 3
guess_attempts = 0
game_end = False
i=0 #here i intialized zero
while guess != secret_word_list and guess_attempts != guess_limit:
# if secretWord == "Duck":
if guess_attempts != guess_limit:
# print(random.choice(duck_hint_list))
print(duck_hint_list[i])#indexing
guess = (input("Guess the secret word: "))
guess_attempts += 1
i+=1#incrementing
if guess_attempts == guess_limit:
print("YOU LOSE IDIOT")
else:
print("You Win!")there are some code which i commented that are not in use. if you want new hint each time they you should use indexing which i did above and i also commented the part which i updated.
发布于 2022-07-04 19:20:48
在原始代码中,有些变量和语句没有使用,所以我没有将它们包含在修改后的代码中。通过删除已经显示的提示,解决了在列表中打印新项目的问题,这样就可以防止提示的重复出现。此外,始终更容易使您的条件为一个较明确的循环一个明确的条件,以便您可以更容易地退出循环。希望这能帮到你。
import random
secret_word = "Duck"
duck_hint_list = ["Hint: It's a bird", "Hint: it swims", "Hint: It loves to be in a row"]
guess_limit = 3
guess_attempts = 0
game_end = True #while loop condition
while game_end:
hint = random.choice(duck_hint_list) #picking a random hint from hint list
print(hint)
duck_hint_list.remove(hint) #removing of already shown hint
guess = (input("Guess the secret word: "))
guess_attempts += 1
if guess_attempts == guess_limit:
print("YOU LOSE IDIOT")
game_end = False #while loop condition change (breaking the loop)
elif guess.lower() == secret_word.lower() :
print("You Win!")
game_end = False #while loop condition change (breaking the loop)https://stackoverflow.com/questions/72859599
复制相似问题