Can someone please explain some of that code to me?

Asked

Viewed 82 times

1

The code in question is the bottom one, a lot of it I’m understanding more the loop for confused me, it gets the sequence of the variable, but in print, it informs exactly the sequence that the user typed, as he knows which is the "letter" in the variable index ?

def jogar():
    print("******************************")
    print("**BEM VINDO AO JOGO DA FORCA**")
    print("******************************")

palavra_secreta = "brasil"

while True:
    chute = input("Qual a letra? ")
    chute = chute.strip()
    index = 0
    for i in palavra_secreta:
        if(chute.upper() == i.upper()):
            print("Encontrada sua letra {} na posição {}".format(chute.upper(), index))
        index = index + 1

 if(__name__ == "__main__"):
     jogar()
  • 1

    A string is an iterator, you can see that as a string is an array/list: https://repl.it/repls/TruthfulBusyFanworms

1 answer

3

In the for part he goes through with "i" each letter of the secret word in the case "brazil" so that in each turn the for it will follow the sequence "b" after "r" after "a" and so on. Example:

my typed letter: "s"

position -> [index]

for [0] letter "b"
for [1] letter "r"
for [2] letter "a"
for position 3 [3] letter "s" ->Found my letter "s" at position 4 index 3
for [4] letter "i"
for [5] letter "l"

in case the "i" plays the role of picking each letter one by one, then in the if it compares if the typed letter is equal to some letter of the secret word, if in the case the guy typed the letter "r" when the to rotate each letter of the secret word will find this letter, in the print it shows the letter found and the index of it that will take the position of the for

  • Okay, thanks, I was thinking the same thing trying to understand, but I couldn’t put my thoughts together, thanks for the explanation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.