Poetry Lion
Poetry Lion

Reputation: 53

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.

Upvotes: 0

Views: 46

Answers (2)

nakE
nakE

Reputation: 362

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 ?")

Upvotes: 2

Sultan Singh Atwal
Sultan Singh Atwal

Reputation: 820

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.

Upvotes: 2

Related Questions