2 回答
TA贡献2036条经验 获得超8个赞
您正在尝试使用 X 作为总回合数以及一回合内猜测尝试次数的计数器。为匝数创建一个单独的变量(例如我的示例中的 num_turns)。
您正在修改循环中的变量 x。我还没有看到很多案例表明这是一个好主意。for 循环应该为你做所有的递增。
正如其他人所说, while 循环在这里可能更有意义,因为您正在检查正确答案,直到找到一个或达到最大猜测
您不需要检查 for 循环的结尾并跳出它。
这并不是真正相关,但您正在阅读每次迭代的文件。将它们一次加载到内存中并从那里访问它们会更有效。
我会按如下方式重写代码,但有许多不同的变体可以工作。
import random
# Set these to whatever makes sense for your use case.
max_turns = 5
max_guesses = 2
# Load these from wherever you want. This is just some dumb testing data.
songs = load_songs() # you'll need to write some code to do this
artists = load_artists() # you'll need to write some code to do this
for turn_counter in range(max_turns):
# Pick a random song:
randNum = int(random.randint(0, 11))
song_name = songs[randNum]
artistname = artists[randNum]
print()
print(song_name[0])
print(artistname)
# Prompt for a guess:
song_guess = input("What is the song called?\n> ")
# Let the user guess until they hit the max tries:
guess_counter = 0
correct_guess = False
while True:
if song_guess == song_name:
correct_guess = True
break
guess_counter += 1
if guess_counter>=max_guesses:
break
# Song wasn't guessed correctly and we haven't hit
# the max guesses yet, so try again:
song_guess = input("Incorrect! Try again:\n> ")
# We're out of the while loop, so either the song was guessed
# correctly, or we hit the max number of guesses. Find out which:
if correct_guess:
print("Answer correct!")
else:
print("GAME OVER")
break
添加回答
举报