Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Functions and Looping While Loops

I was trying to use While Loop but encountered a problem which I dont know how to name it

What I want to do is:

  1. print "Goodbye!" if 0 is entered.
  2. print "Thanks for your order!" if 1 is entered.
  3. If any number besides 0 or 1 is input, you will be asked to enter again. For 3 times in a While loop.

But what really happened is that I could not get to the "else" block. Even if I got the number right, it just didn't print out the messages. Can anyone please point out what is wrong with my code?

So here's a part of my code:

confirm_purchase = int(input("Enter 0 to cancel, 1 to procede with your order: "))
attempt = 2
while confirm_purchase != 0 or 1:
    if attempt <= 0:
        print("Too many attempts. Come back later!")
        break
    confirm_purchase = input("{} attempt(s) left. Try again: ".format(attempt))
    attempt -= 1
else:
    if confirm_purchase == 0:
        print("Goodbye!")
    if confirm_purchase == 1:
        print("Thanks for your order!")

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The issue is with the or. You have:

while confirm_purchase != 0 or 1:

which is True if while confirm_purchase != 0 or 1. The latter, 1, is synonymous with True so this expression will always be true.

You need to be explicit:

while confirm_purchase != 0 or confirm_purchase != 1:

# or maybe

while confirm_purchase not in (0, 1):

Post back if you need more help. Good luck!!

Hello, after I fix the code, when I try to run it I still cannot get the messages from my 2nd attempt.

If I get the value correct (0 or 1) at the first attempt, the message is printed. No problem and totally nice! But from the second attempt forward it keeps telling me to retry even if I input the correct value. Help please!

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

It wasnโ€™t obvious, but the first setting of confirm_purchase is typecast to an int. Inside the while loop it remains a string. So, add an int() wrapper or add โ€0โ€, โ€œ1โ€ to the while condition choices.