【问题标题】:how to loop a set amount of times如何循环一定次数
【发布时间】:2015-02-28 20:44:29
【问题描述】:

我正在编写一个模拟游戏单词拼字游戏的代码。我试图做的是它要求用户解读这个词,如果他们失败了,一旦他们获得另一个机会,依此类推 3 次机会。在 3 次机会之后,程序应该告诉他们在机会限制内他们无法猜到,程序应该告诉他们这个词。

rand_artist = artist_names[random.randrange(len(artist_names))]
tries = 0
while tries < 3:
    rand_input = enterbox("Unscrabble the following: {}".
            format(txt), "Word Scrabble")
    if rand_input != rand_artist:
        msgbox("Try again!", "Word Scrabble")
        tries +=1
    elif rand_input == rand_artist:
        msgbox("Congratulations! You guessed the word!")
        tries +=3
    elif tries > 2: 
        msgbox("You used up three chances! The word was {}".
                format(txt), "Word Scrabble!")

【问题讨论】:

  • 您当前的代码出了什么问题?如果有任何错误消息,请将它们包含在您的问题中。
  • 而错误/问题/疑问是?
  • 你应该发布一些可以运行的东西。最好在不使用 gui 小部件的情况下调试逻辑。如果您使用 tkinter,标签和条目小部件会比弹出框更好。

标签: list python-3.x while-loop counter


【解决方案1】:

您的代码有几个问题,在我对该问题的评论中指出了一些问题。以下工作如您所愿。

from random import choice, shuffle
artist_names = ['Renoir', 'VanGogh', 'Rembrant', 'Homer', 'Pyle',]
artist = choice(artist_names)
alist = list(artist)
shuffle(alist)
scram = ''.join(alist)

for tries in range(1, 4):
    guess = input("Unscrabble {}: ".format(scram))
    if guess == artist:
        print("Congratulations! You guessed the word!")
        break
    elif tries < 3:
        print("Try again!")
    else:
        print("Failed three chances! The word was {}.".format(artist))

【讨论】:

  • 有没有办法不间断地使用它?
  • guessed = False 后跟 while tries &lt; 3 and not guessed:。您的原始代码将(not) guessed 编码为tries 的一部分。我认为为两个不同的概念使用两个名称会更清晰。
  • 您没有在第一篇文章中指定“不间断”,我认为我的回答是更好的继续方式。但也许明天。
猜你喜欢
  • 1970-01-01
  • 2019-11-29
  • 2018-06-22
  • 1970-01-01
  • 2019-01-21
  • 2014-12-05
  • 1970-01-01
  • 2013-10-08
  • 2021-10-17
相关资源
最近更新 更多