首页 > 解决方案 > 如何使用来自同一函数的值循环函数?

问题描述

我目前正在创建一个“刽子手”游戏。下面是我开发的一个函数,它返回未使用的字母。但是我不确定如何保存从函数接收到的值,并在它在 while 循环中循环时再次使用它......

这就是它目前正在做的事情。

你好(字)

L(猜测的字母)未使用的字母:ABCDEFGHIJKMNOPQRSTUVWXYZ

A(猜测的字母)未使用的字母:BCDEFGHIJKLMNOPQRSTUVWXYZ

O(猜测的字母)未使用的字母:ABCDEFGHIJKLMNPQRSTUVWXYZ

我需要它来代替它。请注意它如何保留先前字符串/列表的更改。

L(猜测的字母)未使用的字母:ABCDEFGHIJKMNOPQRSTUVWXYZ

A(猜测的字母)未使用的字母:BCDEFGHIJKMNOPQRSTUVWXYZ

O(猜测的字母)未使用的字母:BCDEFGHIJKMNPQRSTUVWXYZ

ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R','S', 'T', 'U','V', 'W', 'X', 'Y', 'Z']

word = input() #word player 2 is trying to guess
guessedletter = input()


def correctguess(): #Prints unused letters
    newABC = []
    newABCstring = ('')
    for x in ALPHABET:
        if x != guessedletter:
            newABC.append(x)
            newABCstring = (newABCstring + str(x))
    print("Unused letters:" + " " + (newABCstring))
   

guesses=6
while guesses<=6 and guesses>0:
    correctguess()
    guessedletter=input()

标签: pythonfunction

解决方案


您应该使用另一个变量来跟踪未使用的字母。这应该可以从您的列表中删除每个字母。

ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R','S', 'T', 'U','V', 'W', 'X', 'Y', 'Z']

word = input() #word player 2 is trying to guess
try:
     guessedletter = input() #this will need somesort of loop around it for the game to continue as well
     RemainingLetters.Contains(guessedletter)
     correctguess(guessedletter)
catch:
     print("You have already used that letter")

RemainingLetters = ALPHABET

def correctguess(x): #Prints unused letters (x is used to get the letter that got guessed

    RemainingLetters.Remove(RemainingLetters.Index(x)) #find the index of the guessed letter and removes it
    print("Unused letters: " + RemainingLetters))

推荐阅读