Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to stop a loop?
#1
How can I add an exit option... I want to be able to select #5 and it exit loop and print me out a total of my selected donuts!

print("Welcome, to Dino's International Doughnut Shoppe!")
name = input("Please enter your name to begin!:")

fileout= open("Dinos.txt", "w")
fileout.write(name + "\n") 


x=input
 
while x!=5:
    print("Please select a doughnut from the following menu:")
    print("1. Chocolate-dipped Maple Puff ($3.50 each)")
    print("2. Strawberry Twizzler ($2.25 each)")
    print("3. Vanilla Chai Strudel ($4.05 each)")
    print("4. Honey-drizzled Lemon Dutchie ($1.99)")
    print("5. No more doughnuts.")
    x = int(input())

    if x > 5:
        print("I'm sorry, that's not a valid selection. Please enter a selection from 1-4.")
        x= int(input())
        
    if x == 1:
        print("How many Chocolate-dipped Maple Puffs would you like to purchase?")
        fileout= open("Dinos.txt","a")
        fileout.write("Chocolate- dipped Maple Puffs\n")
        fileout.write(str("3.50\n"))
        fileout.close()                         
    if x == 2:
        print("How many Strawberry Twizzlers would you like to purchase?")
        fileout=open("Dinos.txt","a")
        fileout.write("Strawberry Twizzlers\n")
        fileout.write(str("2.25\n"))
        fileout.close()
    if x == 3:
        print("How many Vanilla Chai Strudels would you like to purchase?")
        fileout=open("Dinos.txt","a")
        fileout.write("Vanilla Chai Strudels\n")
        fileout.write(str("4.05\n"))
        fileout.close()
    if x == 4: 
        print("How many Honey-drizzled Lemon Dutchies would you like to purchase?")
        fileout=open("Dinos.txt","a")
        fileout.write("Honey-drizzled Lemon Dutchies\n")
        fileout.write(str("1.99\n"))
        fileout.close()
    y=int(input())
    fileout=open("Dinos.txt","a")
    fileout.write(str(y))
    fileout.close()

    filein= open("Dinos.txt","r")
    for i in range(0-4):
        for line in "Dinos.txt":
            data = line.split("\n")
            name= data [0]
            itemCode= float(data[1])
            itemPrice = float(data[2])
            itemQty= float(data[3])

    if(y > 1):
        filein= open("Dinos.txt","r")
    for i in range(0-4):
        for line in "Dinos.txt":
            data = line.split("\n")
            name= data [0]
            itemCode= float(data[1])
            itemPrice = float(data[2])
            itemQty= float(data[3])
        Total= y* itemPrice
    if y ==1:
        filein= open("Dinos.txt","r")
    for i in range(0-4):
        for line in "Dinos.txt":
            data = line.split("\n")
            name= data [0]
            itemCode= float(data[1])
            itemPrice = float(data[2])
            itemQty= float(data[3])
        Total=(itemPrice)

    print(name + ", here is your recipt:")
    print("-------------------------------")
    itemCode= filein.readline().strip()
    itemPrice=(filein.readline().strip())
    itemQty= (filein.readline().strip())
    filein= open("Dinos.txt","r")
    for i in range(0-4):
        for line in "Dinos.txt":
            data = line.split("\n")
            name= data [0]
            itemCode= float(data[1])
            itemPrice = float(data[2])
            itemQty= float(data[3])
    print(y),print(itemPrice)
    fileout.close()
    print("-------------------------------")

    if(int(y > 1)):
          filein= open("Dinos.txt","r")
    for i in range(0-4):
        for line in "Dinos.txt":
            data = line.split("\n")
            name= data [0]
            itemCode= float(data[1])
            itemPrice = float(data[2])
            itemQty= float(data[3])
    total=float(y)*float(itemQty)
    fileout.close()
    print("Cost: $",total)
    print("Thank you, have a nice day\n")               
Reply
#2
First, change all prints, for example:
print("How many Chocolate-dipped Maple Puffs would you like to purchase?")
to:
while True:
    try:
        qty = input("How many Chocolate-dipped Maple Puffs would you like to purchase? ")
        total_qty += qty
        break
    except ValueError:
        print('Not a number, try again')
do this for all locations where quantity is needed

then add immediately after line 18:
if x == 5:
    print('total: {}'.format(total_qty) 
and before line 1:
total_qty = 0
Reply
#3
Some observations (some of the following may not apply to this specific home assignment as there may be requirements to write code in specific way but these observations are valid in general):

- row #8: don't use unorthodox assignments like x = input. Why you assign built-in function to x? If you need define x more conventional approach will be x = None or x = 0.

- row #17: you convert user input to int. It will blow up your program if user enters string or float. It will pass if user enters negative integer. Negative integer is not handled in following if-conditions (rows #19-46).

- row #19: this deals only with integers which are larger than 5 but user can enter negative integers as well.

- row #63: do you realize that loop for i in range(0-4): never runs? Python interprets it as range(0,-4) and for quite obvious reasons there is no range. You can try it yourself:

>>> len(range(0-4))
0
>>> len(range(4))
4
>>> for x in range(0-4):
...     print(x)
...
>>> 
- rows #23-46: you repeat same process over and over again. This is not DRY (Don't Repeat Yourself). If you find yourself writing such a code you should understand that something needs to be done differently. Write once, call several times.

- one possibility to separate user input validation and user input handling. Usually input validation implemented as function (I don't know if using functions is allowed in this assignment).

- if user input validation is separated from business logic then you can do something along following lines. This is not functional code, just to give idea how you can avoid repeating yourself (from Python 3.6 dictionaries are insertion ordered and from 3.7 they are guaranteed to be insertion ordered):

>>> choices = {1: {'name': 'Chocolate-dipped Maple Puff', 'price': 3.50}, 
...            2: {'name': 'Strawberry Twizzler', 'price': 2.25}, 
...            3: {'name': 'Vanilla Chai Strudel', 'price': 4.05}, 
...            4: {'name': 'Honey-drizzled Lemon Dutchie', 'price': 1.99} 
...            }
>>> for k, v in choices.items(): 
...    print(f"{k}. {v['name']} (${v['price']} each)")
...
1. Chocolate-dipped Maple Puff ($3.5 each)
2. Strawberry Twizzler ($2.25 each)
3. Vanilla Chai Strudel ($4.05 each)
4. Honey-drizzled Lemon Dutchie ($1.99 each)

# user choice is validated separately; after validations choice should be int in specific range; for example user_choice = 2
# qty should be validated as well

>>> qty = input(f"How many {choices[user_choice]['name']} would you like to purchase:  ")
How many Strawberry Twizzler would you like to purchase: 5

# how to write to file

>>> with open('Dinos.txt', 'a') as f:
...     f.write(f"{choices[user_choice]['name']}\n")
...     f.write(f"{choices[user_choice]['price']}\n")
This way you can avoid repetition. Also it enables you change pricing and add new items in one obvious place (this is needed in real life but not in home assignments)

NB! In order this code to work Python version must be 3.6 or higher (usage of insertion ordered dictionaries and f-strings)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to stop an infinite loop in spyder if it's currently running? wlsa 3 24,676 Jun-30-2018, 03:27 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020