简体   繁体   中英

Python: Can't get it to loop back to where I want it

When the user enters numbers whose total is greater than 2000, the code is supposed to reset back to 0 and then continue to ask for numbers until the sum equals exactly 2000. My code resets the total back to 0 but stays at 0 and won't add any of the users input to the total. I know it's a loop issue, I just can't figure out how to get it to loop back to 0 and start again. I purposely have "print(total)" as the last line of code so that I could see what was happening to the total.

my_list = []
print "Rules of the game, keep adding numbers to get exactly 2000!"

while True:
     numbers = raw_input(" Please enter a number: ")

     total = 0

     for num in numbers.split():
         my_list.append(int(num))

     for value in my_list:
         total += int(value)

     if total < 2000:
        print "Current total:"
        print(total)
     elif total == 2000:
        print " Congratulations!"
        break
     elif total > 2000:
        total = 0
        print "Sorry you went over. Try Again."
        print(total)

Example of execute)

Rules of the game, keep adding numbers to get exactly 2000!
 Please enter a number:  2002
Sorry you went over. Try Again.
0
 Please enter a number:  10
Sorry you went over. Try Again.
0
 Please enter a number:  50
Sorry you went over. Try Again.
0
 Please enter a number:   

That's because you reset it to zero every time. Put the decleration of the total variable outside the loop that will solve it:

total = 0
while True:
     numbers = raw_input(" Please enter a number: ")
     ...etc...

Another problem you have is that value_list stays the same . You keep adding numbers to it, and you add all the numbers again every round. Lets say you insert 1 at the first round? So now total is 1 as well. Add 1 again, and now total will be 3 and not 2. Because you add 1 for this round from the last one. So instead of appending to mylist, just recreate if every loop. In other words - put mylist inside the loop:

total = 0
while True:
    numbers = raw_input(" Please enter a number: ")
    mylist = []
elif total > 2000:
    total = 0

When you reset total to 0, my_list still contains all the previous numbers (whose total exceed 2000), thus, from this point on, your total will always exceed 2000.

Solution: you must reset my_list as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM