How can i stop this Infinite While Loop - Python

Irv Kalb Irv at furrypants.com
Wed Oct 30 11:28:37 EDT 2019


> On Oct 30, 2019, at 4:55 AM, ferzan saglam <ferzans97 at gmail.com> wrote:
> 
> I have tried many ways to stop the infinite loop but my program doesn't seem to stop after 10 items! It keeps going...!)
> 
> ---------------------------
> total = 0                                       
> while True:                                     
> 
>  print('Cost of item')                                    
>  item = input()                                        
> 
>  if item != -1:                                        
>    total += int(item)                                      
>  else:                                     
>    break                                       
> 
> print(total)
> ---------------------------
> 
> 
> The output I am aiming for is for the code to stop asking 'Cost of item' after 10 inputs or until -1 is typed, but the code repeats itself on an infinite loop. I cannot seem to stop the infinite loop.
> 
> Thanks for any help in advance.
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 


Perhaps some pseudo-code will help.

The basic problem involves a loop, as you recognized, but there are two ways to exit the loop:

1)  if the user types "-1"

2)  if the user gets to 10 items

Your code needs to account for both.  Here's an description of the solution:


Initialize a total at zero
Initialize a counter at zero    # the user has entered zero prices
Loop forever

      Ask the user to enter a price or type a -1 to indicate that they are finished
      Convert the user's answer to an integer (assuming all values are integers here)
      if the user's answer was -1
          exit the loop here

      Add the user's answer to your total
      Since the user has given you another answer, increment the counter
      if the user has given you the maximum number of answers
           exit the loop here

Report the total (and perhaps the number of prices entered)


Hope that helps,

Irv


More information about the Python-list mailing list