Python Forum

Full Version: (New to Python) Shopping List Code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I stop this code when -1 is typed or at a maximum item count of ten.
At the moment the code seems to be in a infinite loop meaning it keeps on asking for an entry until -1 is typed

total = 0	 	       	  	  	  	    	   	
while True:	 	       	  	  	  	    	   	
	 	       	  	  	  	    	   	
  print('Cost of item')	 	       	  	  	  	    	   	
	 	       	  	  	  	    	   	
  item = input()	 	       	  	  	  	    	   	
	 	       	  	  	  	    	   	
  if item != -1:	 	       	  	  	  	    	   	
    total = total + item	 	       	  	  	  	    	   	
  if item == -1:	 	       	  	  	  	    	   	
	 	       	  	  	  	    	   	
      break	 	       	  	  	  	    	   	
	 	       	  	  	  	    	   	
print(total)
input() will return str. You need to convert it to int or float to calculate total and perform the comparison.
or convert it just for calculations but compare user input with str '-1'
With Python 3.8 one can write following code (max 10 items or cancel with -1):

lst = []

while (item := input('Cost of item: ')) != '-1':
    lst.append(int(item))
    if 9 < len(lst):
        break

print(sum(lst))
Since it seems your question has been answered I'm going to give you some tips. When you are checking with if statements, use else and elif unless you have to use two different if statements for a reason. So the if statement in your code should look like this
if item != '-1':                                        
    total = total + int(item)                                        
else:                                        
    break
Another thing, you can add more easily using the += operation (same thing with -=, *=, /=, etc.). So you can add to your total this way total += int(item)
Instead of printing and then asking for input, use the new line symbol like this item = input('Cost of item\n') this will shorten the code some more
Lastly, whenever accepting input and expecting a certain type of answer, it's best to make sure they are giving the correct type of answer. In this case, the code expects a float answer. You can use a try and except and make sure that a float answer was given. Here's an example:
while True:
    num = input('Enter a number\n')
    try:
        float(num) #If the answer is a number, the float should work on it and it will continue to the next line
        break #This will break out of the while loop
    except: #If there was an error (Their answer wasn't properly floated) meaning they didn't answer with a number
        print('Invalid Answer') #Tell them they entered an invalid number and then the while loop will restart
I hope this helps you