【问题标题】:Keep calling a function until a condition is met Python继续调用函数,直到满足条件 Python
【发布时间】:2019-12-23 18:54:21
【问题描述】:

我想创建一个刽子手游戏。我希望它继续调用 x 并打印 new_word 直到没有“_”。我已经尝试过了,但插槽不断刷新。它一直在重印。它不会更新值本身。

word = 'EVAPORATE'
wordlist = list(word)
dict = dict(enumerate(wordlist))

slots = list('_' * len(word))

x = input("Guess the letter: ")

def game():    
    for a,b in dict.items():
        if b == x:
            slots[a] = x
            new_word = ' '.join(slots)
    print(new_word)

game()

【问题讨论】:

标签: python python-3.x if-statement while-loop return


【解决方案1】:

这似乎对我有用:

word = 'EVAPORATE'
wordlist = list(word)
dict = dict(enumerate(wordlist))
slots = list('_' * len(word))
def game():    
    while '_' in slots:
        x = input("Guess the letter: ")
        for a,b in dict.items():
            if b == x.upper():
                slots[a] = x
                new_word = ' '.join(slots)
        print(new_word)
game()

我在def game(): 内添加了一个while 循环,这样代码将继续运行,直到插槽中没有下划线。然后我将x = input("Guess the letter: " 移动到while 循环内,这样用户就可以随时进行另一个猜测,直到单词完成。

【讨论】:

    【解决方案2】:

    补充几点:

    1. 您永远不要对变量使用诸如 listdict 之类的关键字
    2. 你必须计算每个字母的匹配,例如E出现两次,所以,你必须计算两次
    3. 你必须知道游戏何时结束,因为你想循环“猜信”这个问题直到游戏结束
    4. 添加 While 循环
    5. 享受你的游戏

    word = 'EVAPORATE'
    wordlist = list(word)
    word_length = len(word)
    word_dict = dict(enumerate(wordlist))
    
    slots = list('_' * len(word))
    
    def game():
      total_letters = word_length
      while not game_ended(total_letters):
        x = input("Guess the letter: ")
        matchs = 0
        for pos,letter in word_dict.items():
          if letter == x:
            matchs += 1
            slots[pos] = x
            new_word = ' '.join(slots)
        total_letters -= matchs
        print(new_word)
    
    def game_ended(word_len):
      return word_len == 0
    game()
    

    【讨论】:

    • 我无法将 MD 格式设为代码,有人可以帮我编辑我的帖子吗?
    • 不知道为什么会这样,在使用编号列表之前一定发生在我身上。
    【解决方案3】:

    只需将 input 中的所有内容放入 while 循环中

    word = 'EVAPORATE'
    wordlist = list(word)
    
    # it is not a good idea name a variable the same as a builtin, so change from 'dict' to 'worddict'
    worddict = dict(enumerate(wordlist))
    
    slots = list('_' * len(word))
    
    def game(x):    
        # we also need to change it here
        for a,b in worddict.items():
            if b == x:
                slots[a] = x
                new_word = ' '.join(slots)
        print(new_word)
    
    while any([i == '_' for i in slots]):
        x = input("Guess the letter: ")
        game(x)
    
    

    while检查slots中是否有字母是_,如果有,继续玩。

    请注意,我还将input 作为变量传递给游戏(这不是必需的,但更好)

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2016-11-02
      • 1970-01-01
      • 2021-12-24
      • 2017-02-03
      相关资源
      最近更新 更多