简体   繁体   中英

Input combined with a while-loop

I create a lot of simple functions and programs for myself; this is one of the functions that I like to use a lot because of its simplicity.

answer = True

while answer:
    user = input ("name: ")
    if user == "John":
        answer = False
    else:
        print ("who are you ?")

The function does everything that I need it to. The while-loop remains until the correct answer is given. As I am still a beginner, I would like to know if this is good coding style or if there is maybe a more elegant way of doing this.

Any comments or tips would be greatly appreciated.

Thanks.

You can achieve the same functionality by trying this:

while True:
    user = input ("name: ")
    if user == "John":
        break
    else:
        print ("who are you ?")

You can also try this:

while True:
    user = input ("name: ")
    if user != "John":
        print ("who are you ?")
    else:
        break

In both of these implementations, while True: is being used to run an infinite loop and break is being used to exit the loop if the specified conditions are fulfilled.

You can achieve what you want to do by typing break statement, break will break the loop and continue.

Try this:

while True:
    user = input ("name: ")
    if user == "John":
        break
    else:
        print ("who are you ?")

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