so I've been working on this code for a little bit just to test my abilities and I've run into a brick wall. For some reason my code is breaking out of my for loop. If I say I want to see how much 2 rooms cost it goes through the first one fine but them asks me how many rooms I want to check again. If I input 2 again, it will go through it once and then go on through the rest of the code normally. I have two for loops setup the exact same as each other but for some reason one works and the other doesn't. I'm probably making a stupid mistake but I've been trying to fix it for ages now but no cigar. Appreciate all help!
def start():
print ("Welcome to Caroline's Painting and Decorating cost estimator")
print ("Here you can see an estimate to see how much the job will cost")
print ("First though, you have to enter a few details about the job")
customerNumber = input ("Please enter your customer number ")
dateofEstimate = input ("Please enter the current date ")
def roomCalculator():
surfaceAreaCost = 0
totalPrice = 0
price = 0
count = 0
rooms = int(input("Please enter the number of rooms that require painting "))
for i in range(0, rooms):
roomName = input ("What room needs decorating? ")
wallsNumber = int(input("How many walls are in the room? "))
wallpaper = input ("Is there any wallpaper thats needs to be removed? Enter Y for yes and N for no ")
if wallpaper == "Y".lower():
surfaceAreaCost + 70
for i in range(0, wallsNumber):
count = count + 1
print ("Please enter the dimensions for wall", count)
height = int(input("How high is the wall? "))
width = int(input("How long is the wall? "))
surfaceAreaWall = height*width
wallCost = surfaceAreaWall * 15
price = surfaceAreaCost + wallCost
employeeType = input ("What employee would you like? Enter AP for apprentice or FQ for Fully-Qualified ")
if employeeType == "AP".lower():
price = price + 100
print ("You are having an apprentice do the job")
print ("The price for the", roomName, "without V.A.T is", price)
return price
elif employeeType == "FQ".lower():
price = price + 250
print ("You are having a Fully-Qualified employee to do the job")
print ("The price for the", roomName, "without V.A.T is", price)
return price
Your error is a result of nested for loops, because you use variable i in both. This causes an error since you change value of variable i in first for loop with second for loop. Rename variable in second for loop with j for instance.
Thanks all for the help! It was a stupid error on my part. I used 3.4.4 at my school computer and 3.5.1 at home. It all worked anyway.
Related
I'm asked to ask continuously if the user wants to continue adding the price of a product, and when the answer is no, i have to show the total price of all the products entered. Right now i have this, but it won't ask continuously, it just breaks after the first question and wouldn't ask for a second, third... times
price = 0
user = input ("Do you want to continue (yes/no):")
if user == "yes":
for x in range(0,1):
price = int( input("Please enter the price of the product" + str(x) + ":"))
print(price)
elif user == "no":
print("Your total price is: " + price)
price, num = 0, 0
user = 'yes'
while user == 'yes':
price += int(input(f"Please enter the price of product {num}:"))
user = input ("Do you want to continue (yes/no):")
print("Your total price is: " + price)
maybe the code above will serve ur purpose.
for the variable 'num', I add it because I assume u may want to record the order of the products
beginner here, im currently creating a coffee shop program in pycharm where the costumer inputs the product and then the program sums up all of the price. Im trying to loop the program with the use of functions so the customer can order a many as they want. But when i inputted def main(): in the program, the program under the function does not continue when i run it and i made sure that the codes under the function are indented. Any help would be appreciated thanks enter image description here
here's the code, sorry
print("Good day!, welcome to Avenida's coffee shop")
print("Before i take you order, may i know your name?")
name = input("Input name here: ")
print(
"Hello there " + name + "!, to get started we sell different kinds of food here, we sell coffee, frappe, cake, and pastas")
print("To access our menu, input your preferred food below")
def main():
total_price = 0
category = input("Input your preferred food here: ")
if category.lower() == "coffee":
print("Coffee Menu:")
print("1 Cappuccino = $2")
print("2 Espresso = $2.50")
print("3 Latte = $3")
coffee_input = input("Input the assigned number of the coffee that you would like to order: ")
if int(coffee_input) == 1:
print("How many cappuccino would you like to order?")
coffee_quantity = input("Input here: ")
coffee_total = float(coffee_quantity) * 2
print("That would be $" + str(coffee_total))
total_price = total_price + coffee_total
if int(coffee_input) == 2:
print("How many espresso would you like to order?")
coffee_quantity = input("Input here: ")
coffee_total = float(coffee_quantity) * 2.50
print("That would be $" + str(coffee_total))
total_price = total_price + coffee_total
if int(coffee_input) == 3:
print("How many latte would you like to order?")
coffee_quantity = input("Input here: ")
coffee_total = float(coffee_quantity) * 3
print("That would be $" + str(coffee_total))
total_price = total_price + coffee_total
Try adding this to the end of your code, outside of your main loop. You defined a function called main, but you did not execute it, thus the issue.
if __name__ == '__main__':
main()
My program has errors and bugs that I need to fix. It's about a "robot" that is a waiter in a restaurant. I am still a beginner.
I tried looking through my program for the bugs and tried indenting and dedenting different parts of my program to try and get it working. I als o tried messing around with the operators but nothing seems to work.
import sys, time
total = 0
menu = ["0 - Swedish Meatballs - 5$", "1 - Japanese Sushi - 7$", "2 - Indian Rice - 9$", "3 - Quit"]
price = [5,7,9,0]
print("Hello welcome to the restaurant! I am your robotic waiter")
action = int(input("What would you like to do? \n 1. Look at the menu \n 2. Order \n 3. Take more time \n 4. Ask for the total \n 5. Exit \n Please enter a number here: "))
while action != 5:
if action == 1:
print(menu)
action = int(input("What would you like to do? \n 1. Look at the menu \n 2. Order \n 3. Take more time \n 4. Ask for the total \n 5. Exit \n Please enter a number here: "))
elif action == 2:
print(menu)
food = int(input("What would you like? "))
while food != 3:
priceoffood = price[food]
total = total + priceoffood
if food != 3:
more = input("More things? Reply with y or n: ")
if more == "y":
print(menu)
food = int(input("What would you like? "))
if priceoffood != 3:
print(food)
print(price[food])
priceoffood = price[food]
total = total + priceoffood
else:
break
elif action == 3:
time = int(input("How many minutes more do you need? "))
while int(time) > 30:
print ("Isn't that too long? ")
time = input("How many minutes more do you need? ")
print("Okay, ill be back when your " + str(time) + " minutes are over!")
time.sleep(time*60)
elif action == 4:
print("Your total is: " + str(total))
quit()
I would like the menu functions to be working just like how they are expected to be.
You imported time, but also used it as a variable. Change your variable to something other than time. For example:
timer = int(input("How many minutes more do you need? "))
while int(timer) > 30:
print ("Isn't that too long? ")
timer = input("How many minutes more do you need? ")
print("Okay, ill be back when your " + str(timer) + " minutes are over!")
time.sleep(timer*60)
When I use this code, my aim is to try and make sure that any input will not break the code like letters or numbers not between 0-3. But when i use this code the whole list isn't coming up. How would i fix this?
The output should look like this
Hello Megan the four games avaliable are:
0 Mario Cart
1 Minecraft
2 Angry Birds
3 Grabd Theft Auto
What number game do you want? h
Please choose a valid number
What number game do you want? 23
Please choose a number between 0 and 3
What number game do you want? 1
You have chosen Minecraft
Instead, the output is
Hello the four games avaliable are:
0 Mario Cart
What number game do you want? 2
1 Minecraft
What number game do you want? h
Please enter a valid value
The code i am using is:
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
try:
gametype = int(input("What number game do you want? "))
while gametype <0 or gametype >3:
print (" Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a valid value " )
return gametype
game ()
I have also tried another way, using 'while True' before 'try' but the program says that is an invalid syntax.
SECOND TRY
I have used this new code, but again it won't let me run the code as it says I have an invalid syntax when I put While True, with True highlighted in red.
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
while True:
try:
gametype = int(input("What number game do you want? "))
if 0 <= gametype <= 3 :
return game
print ("Please enter a value between 0 and 3 ")
except ValueError:
print ("Please enter whole number from 0 to 3 " )
return game
game ()
I think you want something like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
for gamenum, gamename in enumerate(gamelist):
print(gamenum, ":", gamename)
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
demo output
What's your name? Megan
Hello, Megan, the four available games are:
0 : Mario Cart
1 : Minecraft
2 : Angry Birds
3 : Grand Theft Auto
What number game do you want? 4
Please enter a value between 0 and 3
What number game do you want? Minecraft
Please enter a whole number from 0 to 3
What number game do you want? 2
You chose Angry Birds
The main change I made to your code is to put the try.. except stuff inside a while True block, so we keep asking for input until we get something valid. I also used enumerate to print each game with its number. That's neater than your while gamecount < 4: loop.
If you have to print the list of games using a while loop then you can do it like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
gamenum = 0
while gamenum < len(gamelist):
print(gamenum, ":", gamelist[gamenum])
gamenum += 1
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
I made gamelist a global list so we can access it outside the game function. We don't need to use the global statement in the function because we aren't changing gamelist. In general, you should avoid using the global statement.
# Vending Machine Simulation
print ("Welcome to the vending machine simulation")
print ("Please enter three coins. Enter as 10 (10p), 20 (20p), 50 (50p) or 100 (£1)")
c1 = int(input("Please enter your first coin: "))
while c1 not in (10, 20, 50, 100):
print("That is not an accepted coin value")
c1 = int(input("Please re-enter your first coin: "))
c2 = int(input("Please enter your second coin: "))
while c2 not in (10, 20, 50, 100):
print("That is not an accepted coin value")
c2 = int(input("Please re-enter your second coin: "))
c3 = int(input("Please enter your third coin: "))
while c3 not in (10, 20, 50, 100):
print("That is not an accepted coin value")
c3 = int(input("Please re-enter your third coin: "))
total = int(c1 + c2 + c3)
print ("You have",total," in credit.")
print ("Thank you for entering your coins. Prices: Hydration: £1, Nutrition: 60p")
Hydration = ("Cola","Fanta","Coffee")
Nutrition = ("Bacon", "Steak","Beans")
print ("Hydration Menu:")
print (Hydration)
print ("Nutrition Menu:")
print (Nutrition)
cost =[]
cost[Hydration] = 100
cost[Nutrition] = 60
pro1 = input ("What would you like, sir/madam?: ")
while pro1 not in (Hydration, Nutrition):
print (total)
pro1 = input ("You entered an invalid term. What would you like, sir/madam?: ")
while cost[pro1] > total:
print ("You do not have enough credit to purchase this product.")
pro1 = input ("What would you like, sir/madam?: ")
if cost[pro1] < total:
total = total - cost[pro1]
print ("Thank you.",total)
pro2 = input ("Would you like anything else, sir/madam?: ")
while pro2 not in (Hydration, Nutrition):
print (total)
pro2 = input ("You entered an invalid term. What would you like, sir/madam?: ")
while cost[pro2] > total:
print ("You do not have enough credit to purchase this product.")
pro2 = input ("Would you like anything else, sir/madam?: ")
if cost[pro2] < total:
total = total - cost[pro2]
print ("Thank you.",total)
pro3 = input ("You have quite the appetite. Would you like anything else, sir/madam?: ")
while pro3 not in (Hydration, Nutrition):
print (total)
pro3 = input ("You entered an invalid term. What would you like, sir/madam?: ")
while cost[pro3] > total:
print ("You do not have enough credit to purchase this product.")
pro3 = input ("Would you like anything else, sir/madam?: ")
if cost[pro3] < total:
total = total - cost[pro3]
print ("Thank you.",total)
I've uploaded my entire code, because I guessed there'd be bits I was leaving out that you needed to know.
I was going to try to put the bits I'm having a problem with in bold, but that didn't work. So,
Hydration = ("Cola","Fanta","Coffee")
Nutrition = ("Bacon", "Steak","Beans")
print ("Hydration Menu:")
print (Hydration)
print ("Nutrition Menu:")
print (Nutrition)
cost =[]
cost[Hydration] = 100
cost[Nutrition] = 60
I'm trying to assign the variables Nutrition and Hydration to the values of 60 and 100 so the program will know how much to take away from your credit, but it keeps returning that the variable 'cost' is not defined. Also, the code doesn't seem to recognise that the products (as seen above) are valid terms despite the fact that they should be connected to the variables Hydration and Nutrition.
As you can see, I'm not very knowledgeable in the art of code. That's why I'm in need of help. Thank you in advance.
you need a dictionary not a list
cost ={}
cost["Hydration"] = 100
cost["Nutrition"] = 60
print cost["Nutrition"]
or maybe you want to associate a cost with each member of the hydration list
costs_hydration = [100,100,100]
costs_nutrition = [60,60,60]
costs = {}
costs.update(dict(zip(Hydration,costs_hydration)))
costs.update(dict(zip(Nutrition,costs_nutrition)))
print costs["Beans"]