继续调用函数直到满足条件Python

时间:2019-08-18 04:51:05

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

我想创建一个子手游戏。我希望它继续调用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()

3 个答案:

答案 0 :(得分:3)

这似乎对我有用:

input

我在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() 内的while循环中添加了代码,这样代码将继续运行,直到插槽中没有下划线为止。然后,我将def game():移到了x = input("Guess the letter: "循环内,以便用户总是可以再猜一次,直到单词完成为止。

答案 1 :(得分: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()

答案 2 :(得分:0)

只需将Character.codePointOf("DNA Double Helix")到末尾的所有内容放入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,如果有,继续播放。

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