【问题标题】:how to return a string from a for loop instead of printing out one by one如何从 for 循环中返回一个字符串,而不是一一打印出来
【发布时间】:2019-10-13 12:30:43
【问题描述】:

我试图让我的 for 循环返回一个带有破折号的整个单词的字符串,或者取决于guess_letters 的每个字母,而不是为我的刽子手游戏一个一个地打印出每个字母。

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

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 列表打印出带有破折号或字母的字符串,但它不会打印任何内容。

【问题讨论】:

  • 预期输出是什么?添加您的问题。
  • dashshow() 未在任何地方调用。该功能有很多错误。解释你为什么创建它以及想要为这两个函数返回什么。简而言之,清楚地解释你的游戏逻辑。
  • 请注意...return 立即停止函数控制流并返回给定结果。运行 return 语句后,该函数中不再运行其他代码。

标签: python for-loop return


【解决方案1】:

你可以这样做。只需根据需要进行修改。此外,您可以将您的代码与此代码进行比较。找出错误。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 2021-12-20
    • 2014-03-06
    • 1970-01-01
    • 2021-12-23
    • 2016-03-27
    • 2019-06-04
    相关资源
    最近更新 更多