Reputation: 53
I am very new to programming and I am just starting out with python. I found some exercises to practice a little bit and i got stuck at while and for loops.
I want to design a program that asks for a donation, and keeps asking for this donation until the minimum amount of 50 euro is donated. WHen this minimum or more is reached i want to stop the program and thank people for the donation.
My code looks like this:
donation = raw_input("enter your donation: ")
while donation < 50:
donation= raw_input("We are sorry that's not enough, enter again: ")
if donation >= 50 print "thank you for the donation"
but this doesn't work at all, i feel like i am missing something completely here.
Who could help me write a working code?
Upvotes: 0
Views: 235
Reputation: 365657
The actual problem with your code has nothing to do with the loop. As David pointed out, you can write that better, but what you have works, it's just a bit verbose.
The problem is that you're comparing strings to numbers. raw_input
always returns a string. And no string is ever less than any number. So, donation < 50
will never be true.
What you need is to turn it into an int
(or float
or Decimal
or some other kind of number, whatever's appropriate):
donation = int(raw_input("enter your donation: "))
while donation < 50:
donation = int(raw_input("We are sorry that's not enough, enter again: "))
if donation >= 50: print "thank you for the donation"
Upvotes: 3
Reputation: 218818
The if
condition within the while
loop shouldn't be necessary at all. The loop will continue until donation >= 50
so you should just be able to print the message after the loop:
donation = raw_input("enter your donation: ")
while donation < 50:
donation= raw_input("We are sorry that's not enough, enter again: ")
print "thank you for the donation"
Upvotes: 3