While loop not working properly when condition is met - python

I am trying to append items to a list, and when I type the word "quit" the loop should stop, and then print the items I have on my list, but the loop continues and still asks me the second question on the loop, which I think should not be happening.
itemName = ''
itemPrice = '0.0'
while itemName != 'quit'.lower().strip():
itemName = input('What item would you like to add?')
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)

I see one problem, you have your .lower().strip on the wrong side.
Also, I would suggest using break so that your code won't ask for a price if quit is inputted.
items=[]
itemName = ''
itemPrice = '0.0'
while True:
itemName = input('What item would you like to add?')
if itemName.lower().strip() == 'quit':
break
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)

The code only checks if you wrote quit after it asks both questions. Also, you should put your .lower().strip() after the input() function. Your code always lowercases and strips the string 'quit'. You can put an if statement after the first question with a break to prevent your code from asking you the second question after you typed 'quit' for the first question.

Try to study this.
items = [] # storage
totalPrice = 0.0
while True:
itemName = input('What item would you like to add? ')
if itemName.lower() == 'quit':
break
itemPrice = input(f'What is the price of {itemName}? ') # ask the price before saving the item
if itemPrice.lower() == 'quit':
break
totalPrice += float(itemPrice) # convert str to float
items.append(f'{itemName} $ {itemPrice}') # Save to storage
print('items:')
for item in items:
print(item)
print()
print(f'total price: $ {totalPrice}')
Output
What item would you like to add? shoes
What is the price of shoes? 600.75
What item would you like to add? bag
What is the price of bag? 120.99
What item would you like to add? quit
items:
shoes $ 600.75
bag $ 120.99
total price: $ 721.74

Related

Extracting a tuple value from a dictionary in python

am working on a restaurant project, and I need a hand :)
so the program will display the main dishes, and the user has to enter which dish he/she wants..
and then the choice will be taken and then added to the bill (dish name, price, num of items)...
so far I chose a dictionary so when the user enters 1 (key), the program will display Mashroum Risto...
this what've created:
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:['Spagehtie',4.850]}
now my question is how to get the dish name without the price (the price is 3.950) and extract it! and also how to get the price without the name so then I can send it into the bill function to calculate it? and if you have any suggestions please go ahead, because i don't know if using dictionary was the right choice
def MainDish():
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:
['Spagehtie',4.850]}
dishes.values
print("1. Mashroum Risito 3.950KD")
print("2. Tomato Pasta 2.250KD")
print("3. Spagehtie 4.850KD")
choice = eval(input('Enter your choice: '))
NumOfItem = eval(input('How many dish(es): '))
while(choice != 0):
print(dishes.get(choice)) #to display the item only without the
price
a = dishes.values()
recipient(a)
break
The way you have implemented it:
print (dishes[1][0]) #will give you name
print (dishes[1][1]) #will give you price
where [x][y]
x = key in the dict (input in your case)
y = element of the value in the dict (0 = name, 1=price in your case)
You should probably create the dictionary better as below:
Follow up question is not so clear but I think this is what you are after roughly. You will need to tweak the returns to your usage:
def MainDish():
NumOfItem = float(input('How many dish(es): '))
dish = list(dishes)[choice-1]
cost_of_dish = dishes[dish]
totalcost = cost_of_dish * NumOfItem
print (f"\n\tOrdered {NumOfItem}x {dish} at {cost_of_dish}KD each. Total = {totalcost}KD\n")
return dish, cost_of_dish, totalcost
dishes = {'Mashroum Risito': 3.950, 'Tomato Pasta': 2.250}
for key,val in dishes.items():
print (f"{list(dishes).index(key)+1}. {key}: {val}KD")
keepgoing = True
while keepgoing:
choice = int(input('Enter your choice: '))
if choice == 0:
keepgoing = False
break
else:
dish, cost_of_dish, totalcost = MainDish()

How to convert pseudo code to Python 2.x?

Here is the pseudo-code for an Over Produced Management System:
Add memory library module
Prompt; 1)search for item, 2)add over produced item
If search for item
Prompt input item number
If item number in database print available quantity
Else print “None available”
Else if add over produced item
Prompt input item number
If item number in database
Prompt “how many”
Add quantity to inventory
Else if item number not in inventory
Add item to inventory with quantity
db = {}
while True:
if raw_input("Prompt; 1)search for item, 2)add over produced item > ") == "1":
item = raw_input("Item number? > ")
if item in db:
print("Available: " + str(db[item]))
else:
print("None available")
else:
item = raw_input("Item number? > ")
qty = int(raw_input("Quantity? > "))
if item in db:
db[item] += qty
else:
db[item] = qty

Line breaks with lists

I have a working script but it does not work the way I want it to:
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "nothing":
print('There are ' + str(len(basket)) + ' items in the basket: '+ str(basket))
break
else:
basket.append(myInput)
print('Okay, what else?')
The final line is supposed to look like this:
There are 3 items in the basket:
Item 1: a sandwich
Item 2: two cans of Dr Pepper
Item 3: some napkins
Any suggestions?
Use enumerate with a start index of 1 and str.format:
while True:
myInput = input()
if myInput == "nothing":
print('There are {} items in the basket: '.format(len(basket)))
for ind, item in enumerate(basket,1):
print("Item{}: {} ".format(ind,item))
break
else:
basket.append(myInput)
print('Okay, what else?')
You can also use a list comprehension and iter without needing a while loop, it will keep looping until the user enters the sentinel value "nothing":
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = [ line for line in iter(lambda:input("Please enter an item to add"), "nothing")]
print('There are {} items in the basket: '.format(len(basket)))
for ind,item in enumerate(basket,1):
print("Item{}: {} ".format(ind,item))
I think its better to separate collecting input and printing the results as follows:
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "nothing":
break
else:
basket.append(myInput)
print('Okay, what else?')
print('There are ' + str(len(basket)) + ' items in the basket: ')
for i,item in enumerate(basket):
print("Item {}: {}".format(i+1, item))
An empty string (just a carriage return) will still be considered an item, even though nothing will be there, which will cause an incorrect # of items in your basket and an empty Item line to be printed. Consider catching that and ignoring it, or potentially making it equivalent to "nothing" in the second if statement as part of the break condition.
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "":
continue
if myInput == "nothing":
print('There are ' + str(len(basket)) + ' items in the basket:')
for itemno, item in enumerate(basket):
print("Item {0}: {1}".format(itemno+1,item))
break
else:
basket.append(myInput)
print('Okay, what else?')

While loop not ending

def getStocks():
stockNames = []
stockPrices = []
done = 0
while done != 1:
stock = input('Enter Stock symbol: ')
if stock == 'done':
done = 1
else:
price = int(input('Enter Price of Stock: '))
print("")
stockNames.append(stock)
stockPrices.append(price)
return stockNames, stockPrices
The issue is that "Enter Stock symbol: " appears even after the user types 'done', how can I get the infinite loop to terminate at this point? I tried using break but it did not provide the results I was looking for
instead of input use raw_input it will fix the problem
def getStocks():
stockNames = []
stockPrices = []
done = 0
while done != 1:
stock = raw_input('Enter Stock symbol: ')
if stock == 'done':
done = 1
else:
price = int(input('Enter Price of Stock: '))
print("")
stockNames.append(stock)
stockPrices.append(price)
return stockNames, stockPrices
python version: 2.7+
you probably want raw_input(), as input() will actually try to evaluate the expression it gets back.

In Python, how do I create a new variable each time a loop goes around, and then send them all to a function to be processed?

I'm still relatively new to python, and this is probably way out of my ability, but I'm working on a program (For a school programming course) that asks for a new item, the price of that item, and the quantity of that item each time a loop goes around. (The loop will be stopped by typing stop when the program asks if there are more items to process) The program will then sends all those variables to a module I created that will calculate the total cost of each item based on the quantity, and then print out the cost of each item, and the total cost.
My teacher says this is possible, but he doesn't quite know how to do it.
Here's what I have so far (I tried to use a list, but it doesn't seem to be working out):
First Program (total_run.py):
import total_cost
itemname = []
itemprice = []
quantity = []
stop = "go"
while stop != "stop":
itemname.append(input("What is the name of the item?\n"))
itemprice.append(float(input("What is the price of the item?\n")))
quantity.append(float(input("How many of these items are there?\n")))
stop = input("Enter \"stop\" to add up the total")
name,price = total_cost.total(itemname,itemprice,quantity)
totalprice = total_cost.final(itemprice)
#Not sure how to print an unknown number of times
print(name," $",price)
print("Your total is: $", totalprice)
Second Program (total_cost.py):
#Calculates all the costs
itemprice = 0
def total(itemname,itemprice,quant):
itemprice = 0
itemname = itemname
for values in quant:
itemprice *= values
return itemname,itemprice
def final(itemprice):
finalcost = itemprice += itemprice
#I'm not sure on how to add up all the items in a list
return finalcost
Your data structures are wrong. Really you just want a single list of items, and each item in that list is itself a list (or a tuple) of name, price, quantity. Then you can simply add up the prices of each item in the list.
items = []
while stop != "stop":
name = input("What is the name of the item?\n")
price = float(input("What is the price of the item?\n"))
quantity = float(input("How many of these items are there?\n"))
items.append((name, price, quantity))
Now you can easily calculate the total per item, and the overall total:
overall_total = 0
for item in items:
total_price = item[1] * item[2]
overall_total += total_price
You can keep the lists in separately, and then iterate through them with a for loop like so:
costs = []
while stop != "stop":
itemname.append(input("What is the name of the item?\n"))
itemprice.append(float(input("What is the price of the item?\n")))
quantity.append(float(input("How many of these items are there?\n")))
stop = input("Enter \"stop\" to add up the total")
for i in range(len(itemname)):
costs.append(itemprice[i]*quantity[i])
total_cost = sum(costs)
Noteworthy things (can't comment, so part of answer here, sorry):
In total_cost.total, you define itemprice = 0 and then multiply by it itemprice *= values so itemprice will remain 0
You pass itemprice and itemname to the total_cost.total function, and then redefine itemprice = 0 and reassign itemname to itself (doesn't break the code though)
Strings in python can be defined by " or ', and the other will not stop the string. so my_string = "Hello, it's a nice day out" or stop = input('Enter "stop" to total the price up') will work.
You can print an unknown amount of items by iterating through the list with a for loop (as shown above
Cheers
As Daniel said, it's better to pack data about one item into one creature.
He suggests tuple, I suggest class:
class Item:
def __init__(self, name=None, price=None, quantity=None):
self.name, self.price, self.quantity = name, price, quantity
#classmethod
def ask_user(cls):
return cls(input('The name of Item: '), float(input('The price: ')), float(input('How much of Items you have: ')))
def value(self):
return self.price * self.quantinity
def total_value(items):
sum = 0
for i in items:
sum += i.value()
return sum
Also, instead of waiting for "stop", you can wait for End-Of-File
(Linux: Ctrl+D in empty line, Windows: Ctrl+Z, then Enter):
items = []
while True:
try:
items.append(Item.ask_user())
except EOFError: #no mire items to read
break #exit from the loop
except Exception as e: #other error
print(type(e), e) #print its type and the message
print(total_value(items))

Categories

Resources