[Tutor] What's wrong with this code?

Brian van den Broek bvande at po-box.mcgill.ca
Tue Jul 5 09:03:16 CEST 2005


Andre Engels said unto the world upon 05/07/2005 02:44:
>>From the program::
> 
> answer = raw_input("What is the password? ")
> while password != answer:
>     print "The password is incorrect."

<snip Andre's description of the problem with the above OP's code>

> I think you intended to make it so that
> the program kept asking for passwords until the right one was given.
> This is done with:
> answer = raw_input("What is the password? ")
> while password != answer:
>     print "The password is incorrect."
>     answer = raw_input("What is the password? ")


A small thing, but I think that is better as:

while True:
      answer = raw_input("What is the password? ")
      if password == answer:
          break
      print "The password is incorrect."

It probably runs a bit slower, but who cares, as the bottleneck is in 
the chair, not the chip. The advantage is that there is only one 
statement of the prompt to alter if you wanted to change it later.

But, I think this will be one where reasonable people can differ. 
Andre's version does make the semantics of the loop somewhat more obvious.

Best to all,

Brian vdB

<snip>

> Andre Engels

<snip OP's question>




More information about the Tutor mailing list