Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a vending machine problem where the user is offered 3 choices :
water 2. cola 3. gatorade
water = $1.00 , cola = $1.50 , gatorade = $2.00
After taking inputs of quarters, dimes, nickels and pennies from the user , I calculate the total amount in dollars. Now I need to check whether the total amount is sufficient for each of the 3 choices of drinks. If the amount is lesser than the cost, I need to prompt the user to try again, if it is greater then I need to display a message for thee user's change amount. I believe this needs while loop and if, elif, else statements. Below is my program so far :
import sys
print('You have three drinks to choose from this Vending Machine: \n 1. Water \n 2. Cola \n 3. Gatorade')
water = 1.00
cola = 1.50
gatorade = 2.00
choice = 0
while not choice:
try:
choice = int(input('Please select any one of the three choices of drinks (1,2 or 3) from the list above'))
if choice not in (1,2,3):
raise ValueError
except ValueError:
choice = 0
print("That is not a valid choice ! Try again")
if choice == 1:
print("1. water = $1.00")
elif choice == 2:
print("2. cola = $1.50")
elif choice == 3:
print("3. gatorade = $2.00")
qrt = int(input("How many quarters did you insert ?"))
dm = int(input("How many dimes did you insert ?"))
nk = int(input("How many nickels did you insert ?"))
pn = int(input("How many pennies did you insert ?"))
total = qrt/4 + dm/10 + nk/20 + pn/100
Now, I need to check if the total amount (that the user inserted) is greater or lesser than the cost of the drink he selected.
If greater I need to return change (display message for change amount).
If lesser then I need to prompt the user to try inserting coins again.
How can I do that ?
I think this is what you need to do. Also take the logic and modify the code as per your requirement.
Don't just copy it. Hope it helps.
import sys
print('You have three drinks to choose from this Vending Machine: \n 1. Water \n 2. Cola \n 3. Gatorade')
water = 1.00
cola = 1.50
gatorade = 2.00
choice = 0
while not choice:
try:
choice = int(input('Please select any one of the three choices of drinks (1,2 or 3) from the list above: '))
if choice not in (1,2,3):
raise ValueError
except ValueError:
choice = 0
print("That is not a valid choice ! Try again")
if choice == 1:
print("1. water = $1.00")
total_to_be = 1.00
elif choice == 2:
print("2. cola = $1.50")
total_to_be = 1.50
elif choice == 3:
print("3. gatorade = $2.00")
total_to_be = 2.00
qrt = int(input("How many quarters did you insert ?"))
dm = int(input("How many dimes did you insert ?"))
nk = int(input("How many nickels did you insert ?"))
pn = int(input("How many pennies did you insert ?"))
total = qrt/4 + dm/10 + nk/20 + pn/100
# total = round(total, 2)
while total != total_to_be:
if total >= total_to_be:
print(total)
break
else:
print("======================= Please try Again ================================")
qrt = int(input("How many quarters did you insert ?"))
dm = int(input("How many dimes did you insert ?"))
nk = int(input("How many nickels did you insert ?"))
pn = int(input("How many pennies did you insert ?"))
total = qrt/4 + dm/10 + nk/20 + pn/100
Related
The following is a sample of a running program:
Welcome to the Fast Freight Shipping Company shipping rate program.
This program is designed to take your package(s) weight in pounds and
calculate how much it will cost to ship them based on the following rates.
2 pounds or less = $1.10 per pound
Over 2 pounds but not more than 6 pounds = $2.20 per pound
Over 6 pounds but not more than 10 pounds = $3.70 per pound
Over 10 pounds = $3.80 per pound
Please enter your package weight in pounds: 1
Your cost is: $ 1.10
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 5
Your cost is: $ 11.00
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 52
Your cost is: $ 197.60
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 8
Your cost is: $ 29.60
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 3
Your cost is: $ 6.60
Would you like to ship another package <y/n>? t
Invalid Input
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 10
Your cost is: $ 37.00
Would you like to ship another package <y/n>? n
Thank you for your purchase, your total charge is $ 282.90
Goodbye!
This is what I have so far:
charges = 0
answer = "yes"
while (answer == "yes"):
packageWeight = eval (input ("Enter weight of package: "))
answer = input ("Do you have more items to input? <yes/no>? ")
if (packageWeight <=2):
charges = (packageWeight * 1.10)
print ("The cost is: $",charges)
elif (packageWeight >2) and (packageWeight<=6):
charges= (packageWeight * 2.20)
print ("The cost is: $", charges)
elif (packageWeight >6)and (packageWeight<=10):
charges = (packageWeight * 3.70)
print ("The cost is: $", charges)
else :
charges = (packageWeight * 3.80)
print ("The cost is: $", charges)
message = "Thank you for your purchase, your total charge is $"
sum= charges+charges
message += format(sum, ',.2f')
print(message)
print("Goodbye!")
how would I find the sum of all charges? And how would I be able to have the second question come after the cost?
So it would display:
Enter weight of package: 3
The cost is: 6.60
Do you have more items to input? yes/no
I did not quite understand this statement how would I find the sum of all charges, but I solved your second question.
Here is the code:
def get_charges(current_weight):
if (current_weight <= 2):
return (current_weight * 1.10)
elif (current_weight > 2) and (current_weight <= 6):
return (current_weight * 2.20)
elif (current_weight > 6) and (current_weight <= 10):
return (current_weight * 3.70)
else:
return (current_weight * 3.80)
charges = 0
answer = "yes"
while (answer == "yes"):
# Eval is not recommended, use a float and round if needed.
packageWeight = float(input("Enter weight of package: "))
charges += get_charges(packageWeight)
print("Current charges: ", charges)
answer = input("Do you have more items to input? <yes/no>? ")
print(f"Thank you for your purchase, your total charge is ${charges}")
print("Goodbye!")
eval() is not recommended for security reasons, so I changed it to float().
Let me know if you have any questions
The goal of the program is to ask user for input for a number of calories in given meal. Later I would like to add the numbers so that the program remembers the previous input. This is only part of the program, but later it returns back to user_input_calories so user can input calories as many times they want. Probably count_calories should not be zero. Could someone help me with that or add some references that I can take a look at?
start=input('Type add to add a meal:')
while start=='add' or start=='Add':
user_input_calories=input('Enter the number of calories in the meal:')
try:
nr1=int(user_input_calories)
count_calories=0
count_calories=count_calories+nr1
except:
print('You have finised eating for the day')
continue
Here's an example of what Matt Clark wrote in the comment:
start=input('Type add to add a meal: ')
count_calories=0 # Counter outside the loop
while start.lower() == 'add':
user_input_calories=input('Enter the number of calories in the meal (q to quit): ')
if user_input_calories == 'q': # Added a command to end the program and count the calories
print('You have finised eating for the day')
print(f'You ate: {count_calories} calories')
break
try:
user_input_calories = int(user_input_calories) # Try to convert to integer and add the value
count_calories += user_input_calories
except:
print("You didn't enter a number")
Result:
Type add to add a meal: add
Enter the number of calories in the meal (q to quit): 100
Enter the number of calories in the meal (q to quit): 200
Enter the number of calories in the meal (q to quit): 300
Enter the number of calories in the meal (q to quit): q
You have finised eating for the day
You ate: 600 calories
I'm creating this program in python that calculates you total cost according to how much you choose.
so the program is pizza delivery, and the user has to choose their choice of pizza out of the menu.
what I cant figure out is that how to tell python that whatever the users first,second and third choice is, the cost will be 3 dollars and the rest would be 5 dollars.
what I mean in more dept would be that how do i tell python that the users 1st,2nd,3rd choice/input = $3.
I tried writing: menu[0:3] = 3 but that just changes the food in the array/list.
this is a sample of my code(not the full code)
Code :
i = 1
total_cost = 0
while(True):
choice = input("Please Enter Your Choice:")
if(i<4):
price = 3
total_cost = total_cost + price
else:
price = 5
total_cost = total_cost + price
i = i + 1
check = input("Do you want to enter another choice? (y/n)")
if(check=="N" or check="n" or check=="No" or check=="no"):
break
print("Total Cost : $",total_cost)
Output :
Please Enter Your Choice:tea
Do you want to enter another choice? (y/n)y
Please Enter Your Choice:coffe
Do you want to enter another choice? (y/n)y
Please Enter Your Choice:apple
Do you want to enter another choice? (y/n)n
Total Cost : $ 9
Try this function:
def price(choice):
if choice <= 3:
cost = 3
else:
cost = 5
return cost
price(4)
> 5
You can create a counter variable for tracking inputs, increment it after taking each input. And then in the price section of your code, use an if statement to set price to 3 if counter < 4, else set price to 5.
# Create counter variable
counter = 0
# Taking user input code here
counter = counter + 1
# Later when setting price in code
if counter < 4:
price = 3
else:
price = 5
Hope this gives you some ideas, feel free to comment and ask for more clarification if you need to!
You should do something like this:
for i in range(1, number_of_pizza+1):
if i < 4:
total_cost += 3
if i >= 4:
total_cost += 5
According to my understanding of your question, you would want to have the menu items separated in the list as :
menu = ['Cheese', 'Vege delight', 'pineapple', 'pepperoni','meat lovers', 'butter chicken', 'spicy corn delight', 'veg slingshot']
and not in the way in which you had shown it in your image.
*I'm new to python, so be gentle...
Overall issue: I have had an issue in multiple codes I've written lately where lines get skipped and it is obviously an error on my part. I know I must be messing up ordering of something, but I'm just not seeing it. My most recent issue can be found here: Is there any reason Python would skip a line?
Now, I want to write an application to pre-sell a limited number of tickets. Here are the conditions:
"Each buyer can buy as many as 4 tickets. There are a total of 15 tickets that are available to pre-sell. The program should prompt the user for the amount of tickets they want to purchase and then display the number of remaining tickets. Repeat until all tickets have been sold, and then display the total number of buyers."
A similar problem is occurring.
buy = int()
ticket_num = 15
buyers = 0
while ticket_num > 0:
buy = int(input("How many tickets would you like to purchase? "))
if buy > 4:
print("You cannot buy that many (4 max).")
buy = input("How many tickets would you like to purchase? ")
else:
ticket_num = ticket_num - buy
print("There are currently", ticket_num, "remaining.")
buyers = buyers + 1
print()
print("The total number of buyers was:", buyers)
It appears that the print line in the 'else' structure is not being read and I don't quite understand why...
Can anyone lend me any insight into what my overall misunderstanding is..?
I figured it out. I had a couple of things incorrect with this problem:
I did not have enough conditional statements (elif) to cover the requirements
I did not need to have the buy variable gather input again in the if statement because the while loop would already cause the program to prompt for input again.
I did not need to have the buy variable outside the while loop at all, I just had to initialize it before using it in the 'if' statement.
The solution is as follows:
tickets = 15
buyers = 0
print("There are currently", tickets, "tickets available.")
while tickets > 0 :
buy = int(input("How many tickets would you like to purchase? "))
if buy <= 4 and tickets - buy >= 0:
tickets = tickets - buy
buyers = buyers + 1
print("There are", tickets, "tickets remaining.")
elif buy > 4:
print("You cannot buy that many (4 max).")
elif tickets - buy < 0:
print("You can only buy what remains. Please see previous 'remaining' message.")
print()
print("There was a total of", buyers, "buyers.")
buy = int()
ticket_num = 15
buyers = 0
while ticket_num > 0:
buy = int(input("How many tickets would you like to purchase? "))
if buy > 4:
print("You cannot buy that many (4 max).")
#buy = input("How many tickets would you like to purchase? ")
else:
if ticket_num - buy>=0:
ticket_num = ticket_num - buy
print("There are currently", ticket_num, "remaining.")
buyers = buyers + 1
else:
print("There are currently", ticket_num, "remaining. You can buy up to", ticket_num, "tickets")
print()
print("The total number of buyers was:", buyers)
Here is the solution. Problem was you were getting input two times. Firstly below the while. Secondly below at the if statement.
Okay so I am trying to make a game of sticks with python. I am asking the user the amount of sticks for him to input.
I am supposed to include a condition where if the user does input a number between 10 and 100, it will ask him over and over again until he gives in a number between that amount. However, my code ends whenever I do input a number between that such amount.
Also, my initial problem is how to ask the player how many sticks will they take after they select the like amount. It just repeats back to the same question, asking them how many sticks do they wish to have in the game. My initial problem is how to advance to the next part.
print("Welcome to the game of sticks, choose wisely...")
sticks = int(input("Choose the number of sticks(10-100 ): "))
while(sticks >= 10 and sticks <= 100 ):
print("There are %d sticks on the board." % sticks)
sticks = int(input("Choose the number of sticks(10-100 ): "))
take = int(input("How many sticks will you take?(1-3): "))
while(take >= 1 and take <= 3):
print(sticks - take)
take = int(input("How many sticks will you take?(1-3): "))
Does anyone have any familiarity with programming a sticks game? Please don't give me the whole output, just tell me what's wrong. What should I do to make it work?
On this line you test if sticks is a valid number and if it is you stay in the while loop. This seems to be your logic error. You are essentially staying in your while loop when you enter a valid number when you want it the other way around.
#your code
while(sticks >= 10 and sticks <= 100 ):
print("There are %d sticks on the board." % sticks)
sticks = int(input("Choose the number of sticks(10-100 ): "))
in the example below you test if the input is valid and if it is you don't enter the loop. If the input isn't valid you stay in the loop until a valid number is entered.
#updated code
while(sticks < 10 or sticks > 100 ):
print("There are %d sticks on the board." % sticks)
sticks = int(input("Choose the number of sticks(10-100 ): "))
Your first while asks how many sticks you want. you need an if statement that says if the number is acceptable, break, else, do it again.
The second while loop asks how many to take out. It shouldn't repeat. Try using if else statements
You use break
Try This:
https://wiki.python.org/moin/WhileLoop
For example
while(sticks >= 10 and sticks <= 100 ):
print("There are %d sticks on the board." % sticks)
sticks = int(input("Choose the number of sticks(10-100 ): "))
break
take = int(input("How many sticks will you take?(1-3): "))
while(take >= 1 and take <= 3):
print(sticks - take)
take = int(input("How many sticks will you take?(1-3): "))
break