[Python] How Can I Show All Occurrences In A Word?

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    The problem I have with this Hangman Program is that it can't display all the occurrences of a letter in a string and I can't update the word so it adds the letters from the previous guess.

    # Hangman.py
    import random

    word_bank = """astounding psychology crazed
    prodigy jargon internship intelligence fundamentals
    analyst dictionary ransomware facility
    antelope dinosaur""".split()

    alphabet = "abcdefghijklmnopqrstuvwxyz"

    drawing = ["""
    +--+
    |
    |
    |
    === """, """
    +--+
    O |
    |
    |
    === """, """
    +--+
    O |
    | |
    |
    === """, """
    +--+
    O |
    /| |
    |
    === """, """
    +--+
    O |
    /|\ |
    |
    === """, """
    +--+
    O |
    /|\ |
    / |
    === """, """
    +--+
    O |
    /|\ |
    / \ |
    ===
    """]

    words_in_bank = len(word_bank) - 1
    random_num = random.randint(0,words_in_bank)
    word = word_bank[random_num]
    tries = 0
    underscore = "_ " * len(word)

    guess = word
    def add_letter(letter, guess, tries):
    while True:
    if letter in guess:
    index = guess.find(letter)
    if index != 0:
    indexs = index * 2
    guesses = underscore[ :indexs] + letter + underscore[indexs+1: ]
    guess = guess[ :index] + guess[index+1: ]

    else:
    break
    return guesses
    print("HANGMAN ------")

    while True:
    print(drawing[tries])
    print(underscore)
    letter = input("Enter a letter: ")
    if letter in alphabet and len(letter) == 1:
    if letter in word:
    updated_word = add_letter(letter, guess, tries)
    print(updated_word)
    else:
    tries += 1
    print("Wrong :( ")
    else:
    print("You must enter 1 letter from the alphabet! \n")
    continue


    If let's say the word was "analyst", I want the output to be "a _ a _ _ _ _" rather than "_ _ a _ _ _ _". I also want the result to be updated when I enter the correct letter: "a n a _ _ _ _" rather than "_ n _ _ _ _ _".

    I tried to change where I returned the value guesses. However, the code still does not function properly.

    Continue reading...

Compartilhe esta Página