Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 67,464 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 67,464 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.