Search code examples
pythonwhile-loopbreak

Stop the while loop if enter the negative number


I've started with learning Python and now I am stuck with the WHILE loop, so if you could give me some advice, I would appreciate it.

So, this is my code and what I need is to stop the whole code if I enter the negative number and to print ("Wrong entry"), but my code, on entering the negative number, still passes and prints me also ("Avg price:"). I would like not to print ("Avg price is: ") when I enter e.g. (2,3,6, -12) - only to print ("Wrong entry"). I now that my last print is within WHILE loop, but I am trying to find the solutions :) Probably, there is easier solution for this, but as I said I am the newbie and still learning Thank you in advance.

price= int(input("Enter the price: "))

price_list=[]

while price!= 0:
    price_list.append(price)
    if price< 0:
       print("Wrong entry")
       break
    price=int(input())

    price_sum= sum(price_list)
print(f"Avg price is: {price_sum / len(price_list)}")

Solution

  • Using a while/else loop produces your desired behaviour.

    • The code in the else doesn't run if the break in the while loop is encountered

    Code

    price= int(input("Enter the price: "))
    
    price_list=[]
    
    while price!= 0:
        price_list.append(price)
        if price< 0:
           print("Wrong entry")
           break
        price=int(input())
    
        price_sum= sum(price_list)
    else:
        print(f"Avg price is: {price_sum / len(price_list)}")