简体   繁体   中英

python:printing a line for ONLY 1 time in a while loop

I am making a guessing game and I need to program to print the line "only" 1 time in my while True loop. I don't want to put the print("") outside of my loop

while True:
       print("I have picked a number between 1 and 100 you can try to guess it.")

You can set a flag

flag = True

while True:
    print("I have picked a number between 1 and 100 you can try to guess it.")
    if flag:
        print("only")
        flag = False

Simply put a printed bool:

printed = False
while True:
    if not printed:
        print('Hello World!')
        printed = True

your while look may have an else clause per the documentation

https://docs.python.org/3/reference/compound_stmts.html#the-while-statement

also look into break statement

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