如何从for循环中返回一个字符串,而不是一个一个地打印出来

时间:2019-05-28 02:48:18

标签: python for-loop return

我试图让我的for循环返回整个单词的字符串,并根据guess_letters加上破折号或每个字母,而不是在我的man子手游戏中一一打印出来。

我试图将字母打印为字符串,返回字母,然后将变量设置为该函数,然后打印该变量。

import random

words = ['apple','python','parent']
def randomword(words):
  return random.choice(words)
chosenword = randomword(words)
tries = 10


guess_letters = []
def dashshow(guess_letters):
  for letter in chosenword:
    if letter in guess_letters:
      return str(letter)
      string_letter = dashshow(guess_letters)
      print(string_Letter)
    else: 
      return '-'
      dash_letter = dashshow(guess_letters)
      print(dash_letter)


def playgame(tries):
  while  tries != 0 and "_" in chosenword:
    print(f"You have {tries} tries left")
    guess = str(input("Guess a letter of the word")).lower()
    guess_letters.append(guess)
    if guess in chosenword:
      print("You got a letter correct!")
      turns -= 1
    else: 
      print("That letter is not in the word")
      turns -= 1


playgame(tries)

我认为它会根据guessed_letters列表打印出带有破折号或字母的字符串,但不会打印任何内容。

1 个答案:

答案 0 :(得分:0)

这是您可以采取的方法。只需根据需要进行修改。此外,您可以将您的代码与此代码进行比较。发现错误。

import random

words = ['apple','python','parent']
def randomword(words):
    return random.choice(words)
chosenword = randomword(words)
print (chosenword) #this is random word you can delete this line.
tries = 10

guess_letters = []

def dashshow(guess_letter):
    guess_letters.append(guess_letter)
    print(guess_letters) # just to debug you can remove.
    if len(guess_letters) == len(chosenword):
        print("You Won Dear!")
        exit()

def playgame(tries):
  while tries != 0 :
    print(f"You have {tries} tries left")
    guess = str(input("Guess a letter of the word:> ")).lower()
    if any(guess in s for s in chosenword):
      print("You got a letter correct!")
      dashshow(guess)
      tries -= 1
    else:
      print("That letter is not in the word")
      tries -= 1


playgame(tries)