字符串python中的Foreach char

2024-09-27 21:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我更习惯C而不是Python。作为业余时间的事情,我决定用Python制作一个简单的hangman控制台应用程序。玩家1输入一个单词,然后玩家2有5次尝试猜测。说“你好”一旦他们猜出来,就说“d”它会打印出来。如果他们的猜测是“e”,它会打印出“e”。你知道吗

出于某种原因,不管我猜的是正确的还是错误的字母,它只显示一个_

word = input("Player 1, please enter a word: ")
lives = 5
print("Player 2, you have {} lives left.".format(lives))
print("The Word: ", "_ " * len(word))
wordSuccessfullyGuessed = False
while lives > 0 or wordGuessed: 
    guess = input("Player 2, guess a letter: ")
    wordFormatted = ""
    for char in word:
        if char in guess:
            wordFormatted = char + " "
        else:
            wordFormatted = "_ "

    print(wordFormatted)




Tags: in应用程序input玩家事情wordplayerprint
3条回答

这里

def hangman_print(guess_lst, word):
    lst = []
    for x in word:
        lst.append(x if x in guess_lst else '_')
    print(''.join(lst))


hangman_print(['l', 't'], 'telescope')

输出

t_l______
word = input("Player 1, please enter a word: ").lstrip().rstrip().lower()
wordBlank = ['_ ' for char in word]
lives = 5
wordLen = len(word)
wordSuccessfullyGuessed = False
wordFormatted = ""
wordGuessed = False
while lives > 0 or wordGuessed:
    guess = ''
    validGuess = False
    print("Player 2, you have {} lives left.".format(lives))
    while len(guess) != 1 or guess.isalpha() == False:
        guess = input('Enter one letter to guess: ').lower()
        characterIteration = 0
        for char in word:
            if guess == char:
                validGuess = True
                wordBlank[characterIteration] = guess+' '
            characterIteration += 1
    if validGuess == False:
        lives -= 1
    print("The Word: ", ''.join(wordBlank))
    if '_ ' not in wordBlank:
        wordGuessed = True
if wordGuessed == True:
    print('You won! The word was indeed', word)
if wordGuessed == False:
    print("You didn't win this time, the word was",word)

输出:

Player 1, please enter a word: trees
The Word:  _ _ _ _ _
Player 2, you have 5 lives left.
Enter one letter to guess: a
The Word:  _ _ _ _ _
Player 2, you have 4 lives left.
Enter one letter to guess: e
The Word:  _ _ e e _
Player 2, you have 4 lives left.
Enter one letter to guess: t
The Word:  t _ e e _
Player 2, you have 4 lives left.
Enter one letter to guess: r
The Word:  t r e e _
Player 2, you have 4 lives left.
Enter one letter to guess: s
The Word:  t r e e s
You won! The word was indeed trees

在内部for循环中,每次迭代都要重新分配变量wordFormatted。看起来您想将字母或下划线附加到字符串中。请尝试:

for char in word:
        if char in guess:
            wordFormatted += char + " "
        else:
            wordFormatted += "_ "

似乎还需要在while循环的每次迭代中重新分配wordFormatted = ""。这将以每一次猜测来澄清这个词。可能也想看看。你知道吗

相关问题 更多 >

    热门问题