简体   繁体   中英

how can i print something in a for loop only once

I'm making a hangman game and I'm a beginner, I can't figure out how to make the for loop print only once:

for char in word:
    if char in guesses:
        print (char)
        print("correct!")
    else:
        print("_")

So is wanna print "correct" only once but right now it's printing it every time a correct letter is inserted

You might give more info about your code and the input. However, perhaps this can help:

x=[1, 2, 3, 4, 1, 1, 2, 4, 3, 5]

for i in (x):
    if i ==1:
        found=True
        print ("correct!")
        break
    else:
        print ("_")

"break" can stop the loop

You can use a boolean to avoid printing something more than once in a loop:

printed = False
for char in word:
    if char in guesses:
        print (char)
        if not printed:
            print("correct!")
            printed = True
    else:
        print("_")

This will print "correct" if the last guess was in the word and then output the typical hangman string.

if guesses[-1] in word:
    print("correct!")
print(''.join(c if c in guesses else '_' for c in word))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM