This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
d = {}
temp = 10000
total = 0
def Expanse_calculator():
global temp
buy = True
while buy == True:
x = input("Enter the expenditure name:")
if x in d.keys():
price =float(input(f" Enter the '{x}' amount:"))
if temp>=price:
d[x]+=price
temp-=price
else:
print("insufficint found")
break
else:
price =float(input(f"Enter the '{x}'amount:"))
if temp>=price:
d[x]=price
temp-=price
else:
print("insufficint found")
break
total=sum(d.values())
while True:
ip = input("If you want to add any more expenditure [YES|NO]:").lower()
if ip == 'no':
buy = False
break
elif ip == 'yes':
Expanse_calculator()
else:
print("Invalid Entry")
Expanse_calculator()
print(total)
Above is my sample code
While entering 'no' to my query in while loop its not terminating in first attempt
output i'm getting:
Enter the expenditure name:asd
Enter the 'asd'amount:123
If you want to add any more expenditure [YES|NO]:yes
Enter the expenditure name:asf
Enter the 'asf'amount:124
If you want to add any more expenditure [YES|NO]:no
If you want to add any more expenditure [YES|NO]:no
iam new to python plz help.
d = {}
temp = 10000
total = 0
def Expanse_calculator():
global temp,total
buy = True
while buy == True:
x = input("Enter the expenditure name: ")
if x in d.keys():
price =float(input(f" Enter the '{x}' amount: "))
if temp>=price:
d[x]+=price
temp-=price
else:
print("insufficient funds")
break
else:
price =float(input(f"Enter the '{x}'amount: "))
if temp>=price:
d[x]=price
temp-=price
else:
print("insufficient funds")
break
total=sum(d.values())
while True:
ip = input("If you want to add any more expenditure [YES|NO]:").lower()
if ip == 'no':
buy = False
break
elif ip == 'yes':
Expanse_calculator()
else:
print("Invalid Entry")
print(total)
quit()
Expanse_calculator()
Related
Hi I've got a school project which requires me to code a program that asks a user for their details it will then ask what them what size pizza they want and how many ingredients. It will then ask if they want another pizza. It will repeat this until they say no or they have six pizzas.
I don't really know how to explain my issues but I don't know how to loop the code so it asks for another pizza and each one has a different size and amount of toppings. I also don't know how I would print it.
Sorry if this is asking a lot or its confusing to understand or if the code is just painful to look at ahaha.
Thanks in advance.
CustomerName = input("Please input the customers name: ")
CustomerAddress = input("Please input the customers address: ")
CustomerNumber = input("Please input the customers number: ")
while True:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ")
try:
PizzaSize = str(PizzaSize)
if PizzaSize == "Small" or "Medium" or "Large":
break
else:
print("Size not recognized")
except:
print("Invalid input")
if PizzaSize == "Small":
SizeCost = 3.25
elif PizzaSize == "Medium":
SizeCost = 5.50
elif PizzaSize == "Large":
SizeCost = 7.15
print(SizeCost)
while True:
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
ExtraToppings = float(ExtraToppings)
if ExtraToppings >= 0 and ExtraToppings <= 4:
break
else:
print("Please insert a number over 0")
except:
print("Input not recognised")
if ExtraToppings == 1:
ToppingCost = 0.75
elif ExtraToppings == 2:
ToppingCost = 1.35
elif ExtraToppings == 3:
ToppingCost = 2.00
elif ExtraToppings >= 4:
ToppingCost = 2.50
else:
print("Number not recognized")
print(ToppingCost)
``
First of all, you should put the code from the second while loop in the first. There is no need for two while true loops. Then instead of
while True:
just put
pizza_count = 0 # how many pizzas they have
wantsAnotherPizza = True
while pizza_count < 6 and wantsAnotherPizza: # while they have less than 6 pizzas and they want another one
pizza_count += 1 # increase pizza_count as they order another pizza
# ... your code here from both of the while loops
x = input("Do you want another pizza? (Y/N)")
if x == "N" or x == "n":
global wantsAnotherPizza
wantsAnotherPizza = False:
You can modify your code like this. I thing you can simply your conditionals by using dictionaries. Try this
from collections import defaultdict
customer_order = defaultdict(list)
customer_order['CustomerName'] = input("Please input the customers name: ")
customer_order['CustomerAddress'] = input("Please input the customers address: ")
customer_order['CustomerNumber'] = input("Please input the customers number: ")
pizza_size ={
'small':3.25,
'medium': 5.50,
'large': 7.15
}
toppins= {'1': 0.75,
'2':1.35,
'3':2.00,
'4':2.50,
}
order = int(input("How many orders would you like to make: "))
while order:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ").lower()
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
if PizzaSize in pizza_size:
size_cost= pizza_size[PizzaSize]
if ExtraToppings:
ToppingCost= toppins[ExtraToppings]
else:
print("Number not recognized")
continue
customer_order['order'].extend([{'size':PizzaSize,'toppings': ToppingCost}])
order -= 1
else:
print("Size not recognized")
continue
except Exception as msg:
print("Invalid input", msg)
continue
else:
print('Your order is complete')
print(customer_order)
I am currently having issues having my program access my list after the user enters a menu option. the only entry being read is the 1939 entry, any other year will only present the "enter a valid year" option. Another issue is when displaying categories, only the first 2 drama films will pop up, every other category doesn't work when asked for. It also will not display the entire list when I call to display it (only the 1939 entry would pop up). Any help would be very appreciated!
movies = [[1939,'Gone With the Wind','drama'],
[1943,'Casablanca','drama'],
[1965,'The Sound of Music','musical'],
[1969,'Midnight Cowboy','drama'],
[1972,'The Godfather','drama'],
[1973,'The String','comedy'],
[1977,'Annie Hall','comedy'],
[1981,'Chariots of Fire','drama'],
[1984,'Amadeus','historical'],
[1986,'Platoon','action'],
[1988,'Rain Man','drama'],
[1990,'Dances with Wolves','western'],
[1992,'Unforgiven','western'],
[1993,'Schindlers List','historical'],
[1994,'Forrest Gump','comedy'],
[1995,'Braveheart','historical'],
[1997,'Titanic','historical'],
[1998,'Shakespeare in Love','comedy'],
[2001,'A Beautiful Mind','historical'],
[2002,'Chicago','musical'],
[2009,'The Hurt Locker','action'],
[2010,'The Kings Speech','historical'],
[2011,'The Artist','comedy'],
[2012,'Argo','historical'],
[2013,'12 Years a Slave','drama'],
[2014,'Birdman','comedy'],
[2016,'Moonlight','drama'],
[2017,'The Shape of Water','fantasy'],
[2018,'Parasite','comedy']]
menu = """
1 - Display winning movie for a selected year
2 - Display movie and category for a selected year
d - Display entire movie list
dc - Display movies in a selected category - year and title
q = quit
"""
while True:
print(menu)
option = input("Please enter a valid menu option from above: ")
if option in 'qQ':
print("Ending program")
break
elif option == "1":
year = int(input("Please enter a valid year: "))
for m in movies:
if year == m[1]:
print("The winning movie in ", year," was: ", m[1])
else:
print("Input a valid year")
break
elif option == "2":
year = int(input("Please enter a valid year: "))
for m in movies:
if year == m[0]:
print("The winning movie was: ", m[1], "and its category was: ", m[2])
else:
print("Please enter a valid year")
break
elif option == "d":
for m in movies:
print(m[0], m[1], m[2])
break
elif option == "dc":
cat = input("Please enter a valid category")
for m in movies:
if cat == m[2]:
print(m[0], m[1])
else:
print("Please enter a valid category")
break
else:
print()
print("Please select a valid option")
At m[1] pulls movie name and not year.
Converting year input to integer and comparing.
if int(year) == m[0]:
Also, Breaks are used improperly. for display option index are not correctly used.
print(m[0], m[1], m[2])
Corrected Code
while True:
print(menu)
option = input("Please enter a valid menu option from above: ")
if option in 'qQ':
print("Ending program")
break
elif option == "1":
year = input("Please enter a valid year: ")
print(year)
for m in movies:
if int(year) == m[0]:
print("The winning movie in ", year," was: ", m[1])
elif option == "2":
year = input("Please enter a valid year: ")
for m in movies:
if int(year) == m[0]:
print("The winning movie was: ", m[1], "and its category was: ", m[2])
elif option == "d":
for m in movies:
print(m[0], m[1], m[2])
elif option == "dc":
cat = input("Please enter a valid category : ")
for m in movies:
if cat == m[2]:
print(m[1], m[2])
else:
print("Please select a valid option")
Hi i am albert i am learning python, in this block of code i wrote i intend it to print the total, but the input statements just keep going in a loop
print("this program prints your invoice")
while True:
ID = input("item identification: ")
if ID == "done":
break
if len(ID) < 3:
print("identification must be at least 3 characters long")
exit(1)
break
try:
Quantity = int(input("quantity sold: "))
except ValueError:
print("please enter an integer for quantity sold!!!")
exit(2)
if Quantity <= 0:
break
print("please enter an integer for quantity sold!!!")
exit(3)
try:
price = float(input("price of item"))
except ValueError:
print("please enter a float for price of item!!")
exit(4)
if price <= 0:
print("please enter a positive value for the price!!!")
exit(5)
break
cost = 0
total = cost + (Quantity*price)
print(total)
I think you need this
cost = 0
total = cost + (Quantity*price)
print(total)
to be inside the while loop. Else, skip the loop completely.
Try this:
print("This program prints your invoice")
total = 0
more_to_add = True
while more_to_add == True:
ID = input("Item identification: ")
if len(ID) < 3:
print("Identification must be at least 3 characters long")
continue
try:
Quantity = int(input("Quantity sold: "))
except ValueError:
print("Please enter an integer for quantity sold!!!")
continue
if Quantity <= 0:
print("Please enter an integer for quantity sold!!!")
continue
try:
price = float(input("Price of item: "))
except ValueError:
print("Please enter a float for price of item!!")
continue
if price <= 0:
print("Please enter a positive value for the price!!!")
continue
total = total + (Quantity*price)
answer = input("Want to add more? (Y/N)" )
if answer == 'Y':
more_to_add = True
else:
more_to_add = False
print(total)
I have this code and it doesn't run at all. It is a list of objects, and each object has a two dimensional list in it. It is not executing the code to even display just the flightNo element. I've made a method to display the 2d list in the object, but nothing happens. I tested with a simple print('Hello') at the end and that does work. Can someone tell me what could be wrong here?
EDIT: Full code at: https://onlinegdb.com/HJPqXWXWU
elif a == 3:
for i in range(len(FlightList)):
print(FlightList[i].flightNo)
req = input('Enter flight number to buy tickets: ')
for Flight in FlightList:
if Flight.flightNo == req:
for a in range(len(Flight.seats)):
for b in range(len(Flight.seats[a])):
print(Flight.seats[a][b], end=" ")
print()
qty = int(input('Enter number of tickets'))
Flight.buyTicket(one, qty)
print("Hello")
I have also tried a different method to display flightNo, no execution again:
for Flight in FlightList:
print(Flight.flightNo)
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
for a in range(len(i.seats)):
for b in range(len(i.seats[a])):
print(i.seats[a][b], end=" ")
print()
Here is the working code that I modified the location of calling the method and assigning to the variable because every time we have to create a new instance of the class to save data properly and we should not clear the list that's why I changed the position outside of the loop. And this I working properly. for my basic testing. I can improve if you need. and kept your code in the comment's so you can see the change.
import sys
class Flight:
def __init__(self):
self.flightNo = "None"
self.planeType = "None"
self.destination = "None"
self.w = self.h = 0
self.seats = [["None" for x in range(self.w)] for y in range(self.h)]
self.depDate = "None"
self.depTime = "None"
self.eta = "None"
self.ticketsSold = 0
self.pricePerTicket = 0.0
def displayDetails(self):
print('Flight No: ', self.flightNo,
'\nPlane Type: ', self.planeType,
'\nDestination: ', self.destination,
'\nDeparture Date: ', self.depDate,
'\nDeparture Time: ', self.depTime,
'\nETA: ', self.eta,
'\nTickets Sold: ', self.ticketsSold,
'\nPrice: ', self.pricePerTicket, '\n\n')
def totalSales(self):
return print("Total number of tickets sold: ", self.ticketsSold,
"\nTotal sales: ", (self.ticketsSold * self.pricePerTicket))
def buyTicket(self, quantity):
quantity = int(input("Enter number of tickets required: "))
cost = quantity * self.pricePerTicket
for v in range(len(self.seats)):
for j in range(len(self.seats[v])):
if quantity > len(self.seats) * len(self.seats[v]):
print("Lessen the number of tickets")
break
if self.seats[v][j] == "\\__/":
self.seats[v][j] = "\\AA/"
quantity -= 1
if quantity == 0:
break
if quantity == 0:
break
print(quantity, "tickets bought for $", cost,
"\nSeats assigned", )
self.ticketsSold += quantity
# one = Flight()
ans = True
FlightList = []
while ans:
print("----------------------------- \n1. Add a flight \n2. Remove a flight \n3. Sell Tickets",
"\n4. Display seat info \n5. Display total sales for flight \n6. Display flight info",
"\n7. Display all flight's info \n0. Quit")
a = int(input("Enter number: "))
#FlightList = []
if a == 1:
one = Flight()
one.flightNo = input('Enter flight number: ')
one.planeType = input('Enter plane type: ')
one.destination = input('Enter destination: ')
one.w = int(input('Enter number of columns in flight: '))
one.h = int(input('Enter number of rows in flight: '))
one.seats = [["\\__/" for x in range(one.w)]
for y in range(one.h)]
one.depDate = input('Enter departure date: ')
one.depTime = input('Enter departure time: ')
one.eta = input('Enter ETA: ')
one.ticketsSold = int(input('Enter number of tickets sold: '))
one.pricePerTicket = float(input('Price: '))
FlightList.append(one)
elif a == 2:
rem = input('Enter flight number to remove: ')
for i in FlightList:
if i.flightNo == rem:
del FlightList[FlightList.index(i)]
elif a == 3:
for i in range(len(FlightList)):
print(FlightList[i].flightNo)
req = input('Enter flight number to buy tickets: ')
for Flight in FlightList:
if Flight.flightNo == req:
for a in range(len(Flight.seats)):
for b in range(len(Flight.seats[a])):
print(Flight.seats[a][b], end=" ")
print()
qty = int(input('Enter number of tickets'))
Flight.buyTicket(one, qty)
print("Hello")
elif a == 4:
for Flight in FlightList:
print(Flight.flightNo)
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
for a in range(len(i.seats)):
for b in range(len(i.seats[a])):
print(i.seats[a][b], end=" ")
print()
elif a == 5:
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
i.totalSales()
elif a == 6:
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
i.displayDetails()
elif a == 7:
for item in FlightList:
item.displayDetails()
elif a == 0:
sys.exit(0)
Here is my code the lists are where Im having issues. Im new to python and I do not understand how 2D-lists work but I need to add then in to the program for a grade. Any help will be appreciated.
#Define Vars
import locale
locale.setlocale( locale.LC_ALL, '')
order_total = 0.0
price = 3.5
fmt_price = locale.currency(price, grouping=True)
qty = int(0)
#cookie list
cookie_list = list()
cookie_list = "Savannah Thin-Mints Tag-a-longs Peanut-Butter Sandwich".split()
order_list = list()
#cookie choices
def disp_items():
print("Please choose one of our flavours. Enter the item number to choose")
for c in range(len(cookie_list)):
print("{}. \t{}".format(c+1, cookie_list[c]))
print()
#Menu Choices
def disp_menu():
choice_list = ["a", "d", "m", "q"]
while True:
print("\nWhat would you like to do?")
print("a = add an item")
print("d = delete an item")
print("m = display the meal so far")
print("q = quit")
choice = input("\nmake a selection: ")
if choice in choice_list:
return choice
else:
print("I dont't understand that entry. Please Try again.")
# Math Function**********************
def calc_tot(qty):
#this function is qty * price
return qty * 3.5
def disp_order():
print("\nGirl Scout Cookie Order for", cust)
print()
print("Itm\tName\tQty\tPrice")
print("---\t----\t----\t----")
order_total_items = 0 #accumulator
order_price = 0
for c in range(len(order_list)):
detail_list = [" ", 0]
detail_list.append(order_list)
print("{}.\t{}\t{}\t{}".format(c+1, order_list[c][0], order_list[c][1], price))
order_total_items += order_list[c][1]
order_price += price
print("\nYour Order Contains {} items for total of {} \n".format(order_total_items, order_price))
print("-" * 30)
#ADD Process
def add_process():
valid_data = False
while not valid_data:
disp_items()
try:
item = int(input("Enter item number: "))
if 1 <= item <= len(cookie_list):
valid_data = True
else:
print("\nThat was not a vaild choice, please try again.")
except Exception as detail:
print("error: ", detail)
#Valid Qty
valid_data = False
while not valid_data:
try:
qty = int(input("Enter Quantity: "))
if 1 <= qty <= 10:
valid_data = True
else:
print("\nThat was not a valid quantity, please try again.")
except Exception as detail:
print("Error; ", detail)
print("Please try again")
#Function call for multiplication
item_total = calc_tot(qty)
fmt_total = locale.currency(item_total, grouping=True)
#User Choice
print("\nYou choose: {} boxes of {} for a total of {}".format(qty,
cookie_list[item-1],
fmt_total))
print()
#verify inclusion of this item
valid_data = False
while not valid_data:
incl = input("Would you like to add this to your order? (y/n): ")
print()
if incl.lower() =="y":
#2-D List
inx = item - 1
detail_list = [inx, qty]
order_list.append(detail_list)
valid_data = True
print("{} was added to your order".format(cookie_list[inx]))
elif incl.lower() == "n":
print("{} was not added to your order".format(cookie_list[inx]))
valid_data = True
else:
print("That was not a vaild response, please try again")
#Delete function
def del_item():
if len(order_list) == 0:
print("\n** You have no items in your order to delete **\n")
else:
print("\nDelete an Item")
disp_order()
valid_data = False
while not valid_data:
try:
choice = int(input("Please enter the item number you would like to delete: "))
if 1<= choice <= len(order_list):
choice = choice - 1
print("\nItem {}. {} with {} boxes will be deleted".format(choice +1,
order_list[choice][0],
order_list[choice][1]))
del order_list[choice]
valid_data = True
except Exception as detail:
print("Error: ", detail)
print("Please try again")
#Main program
# Banner
print("Welcome to the Girl Scout Cookie")
print("Order Program")
cust = input("Please enter your name: ")
while True:
choice = disp_menu()
if choice == "a":
add_process()
elif choice == "d":
del_item()
elif choice == "q":
break
disp_order()
disp_order()
print("Thank you for your order")
Here's the output
Girl Scout Cookie Order for *****
Itm Name Qty Price
--- ---- ---- ----
1. **0** 1 3.5
2. **0** 1 3.5
3. **4** 5 3.5
Your Order Contains 7 items for total of 10.5
Under name there should be a name of a girl Scout Cookie and not the index number, how do i fix this?
Many Thanks.
When you print the order in disp_order() you should print from cookie_list[c] in the second column. And print the whole item instead off just the first letter.
print("{}.\t{}\t{}\t{}".format(c+1, cookie_list[c], order_list[c][1], price))
The cookie names are not of equal length, so you'll have to adjust for that.