#πŸ”’ confused with while loop

11 messages Β· Page 1 of 1 (latest)

pine grail
#

I am confused as to why the loop started even though I got the correct pin in this scenario. code:

attempts = 0
pin = int(input("PIN: "))        
if pin == 4321:
    print("Correct! It only took you one single attempt!")

while pin != 4321:
    pin = int(input("PIN: "))        
    if pin == 4321:
        attempts += 1
        break
    elif pin !=4321:
        attempts += 1
        print("Wrong")
print("Correct! It took you {} attempts".format(attempts))
topaz mortarBOT
#

@pine grail

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

hardy cipher
#
attempts = 0
pin = int(input("PIN: "))
while pin != 4321:
    pin = int(input("PIN: "))        
    if pin == 4321:
        attempts += 1
        break
    elif pin !=4321:
        attempts += 1
        print("Wrong")
if attempts == 0:
    print("Correct! It only took you one single attempt!")
else:
    print("Correct! It took you {} attempts".format(attempts))
#

furthermore the elif pin != 4321 is redundant

#

if pin is not 4321 then it already must be unequal to 4321

#
attempts = 0
pin = int(input("PIN: "))
while pin != 4321:
    attempts += 1
    pin = int(input("PIN: "))
    if pin == 4321:
        break
    print("Wrong")
if attempts == 0:
    print("Correct! It only took you one single attempt!")
else:
    print("Correct! It took you {} attempts".format(attempts))
pine grail
#

oh I see thanks!

pine grail
#

!close

topaz mortarBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.