Recurring line disappearance, issue with while loop - python

*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.

Related

I want to make a nested loop that makes user enter a number that does not make the input variable have a negative output. How with changing variable?

This is Python in Visual Studio Code. I'm making a program for school that essentially is an robotic restaurant waitress. I have to do it the way the assignment outline says which is why it might be a little weird. Then I have to personalize it and make it creative. It asks how much the price of an adult meal and a child meal. Then it asks how many children and adults there are. Then it asks what the sales tax rate is. The assignment only needs me to be able to calculate all that and get the subtotal and total and then give change. I've already done that and I'm making it fancy. I made a loop that asks if they have a lucky draw coupon that generates a random monetary value between $1.00-$5.00. Then If they say yes it will bring them to the first part of the loop that gives them the total with the coupon and then asks for payment. If they say no, then it just asks them for the payment.
I want to go the extra mile and put a loop in a loop, which I think is called a nested loop (This is my first week of Python.) I want it to recognize if the amount they pay is less then the total, then ask for the user to try again until they put an amount more than the total. Pretty much I just want it to know that the payment isn't enough.
My problem is I've never used nested loops and this is the first time I've even used a loop period. I also don't know how to make a loop based on a variable that's not constant because it's based on what the user inputs when prompted. I could do it if I could put the parameters in a fixed range, but the range will always be different based on what they enter in the beginning.
How do I make a nested loop recognize a variable that is never the same?
How do I make it recognize the payment is not enough to cover the total?
This is the loop I have. And I want to put two nested loops in the loop. One for if and one for elif so that it works for both "options".
Here is my snippet:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
payment = float(input("Please enter your payment amount: "))
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")
Any suggestions? I've searched all over Stackoverflow and google and cannot find anything specific to my situation.
Your approach is good for implementing this. Looping while asking for payment and validating that it is correct before allowing the loop to break will do the job. For your first if block, this is how that would look:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
#Ask for the payment inside of the new loop
while True:
payment = float(input("Please enter your payment amount: "))
if payment - total + coupon > 0:
print("That's not enough money to pay your bill. Try again")
else:
break
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")

Python If Elif Else conditions

If an item to be purchased costs more than $5000 then the purchaser must go to tender (display a message), if the item costs between $500 and $5000 inclusive then the purchaser must get quotes from three different suppliers (display a message), otherwise the purchaser can just go ahead and order the item (display a message).
What I have is leaving out the last bit. I know it is something simple.
cost=int(input("Please Enter The Cost Of The Item You Wish To Purchase: "))
if cost>5000:
print("Your Must Go To Tender")
elif cost<=500 or cost<=5000:
print("Your Must Get 3 Different Quotes")
else:
print("You May Order")
That's because of your elifcondition which should be:
elif cost >= 500 and cost <= 5000:

Using if statements inside while loop in python? [closed]

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

How to use a while loop to add values up?

I'm writing a simple python program that helps users keep track of the number of calories that they consume and displaying whether the user is over or within their calorie goal for the day.
Here's my code so far.
caloriesGoal = float(input('Enter the calorie goal for number of calories for today: '))
numberOfCaloriesConsumed = float(input('Enter the number of calories consumed today'))
totalConsumed = 0
while (numberOfCaloriesConsumed > 1500 and numberOfCaloriesConsumed < 3000):
numberOfCaloriesConsumed = float(input('How many calories did you consumed?'))
totalConsumed += numberOfCaloriesConsumed
count = count + 1
print('Your total calories consumed is: ' , totalConsumed)
if(caloriesGoal > totalConsumed):
print('The user is within their goal by ', (caloriesGoal - totalConsumed))
else:
print('The user exceeded their goal by', (totalConsumed - caloriesGoal))
Try this out, the output is much clearer for what you are expected to enter.
while True:
caloriesGoal = float(input('Enter the calorie goal the day: '))
if 1500 <= caloriesGoal <= 3000:
break
else:
print("Error: Goal must be between 1500 and 3000 calories!")
totalConsumed = 0
items = 0
while True:
caloriesConsumed = float(input('Item {}: How many calories was it? (-1 to stop)'.format(items+1)))
if caloriesConsumed < 0:
print("Input stopped")
break
totalConsumed += caloriesConsumed
items += 1
if totalConsumed > caloriesGoal:
print("Goal reached/exceeded!")
break
print('You consumed {} calories in {} items.'.format(totalConsumed, items))
if caloriesGoal > totalConsumed:
print('The user is within their goal by ', (caloriesGoal - totalConsumed))
else:
print('The user exceeded their goal by', (totalConsumed - caloriesGoal))
Welcome to Python! It was my second language, but I love it like it was my first. There are few things going on in your code that's a little strange.
Something interesting is that you're doing a check on numberOfCaloriesConsumed. If you're entering a Krispy Kreme donut, you're going to enter 190 calories. Let's review your while:
while (numberOfCaloriesConsumed > 1500 and numberOfCaloriesConsumed < 3000):
If we take a look at this line ...
numberOfCaloriesConsumed = float(input('Enter the number of calories consumed today'))
... and we enter 190 for our Krispy Kreme donut, then we won't enter the loop. What you may want to change the while to is an infinite loop with a break mechanism:
while 1:
numberOfCaloriesConsumed = input('How many calories did you consumed?')
if (numberOfCaloriesConsumed == "q") or (totalConsumed > 3000): # keep numberOfCaloriesConsumed as a string, to compare for the break
if (totalConsumed < 1500):
print("You need to eat more!\n")
else:
break
else:
if (totalConsumed + int(numberOfCaloriesConsumed)) > 3000:
print("You eat too much! You're done now!\n")
break
totalConsumed = totalConsumed + int(numberOfCaloriesConsumed) #make the string an int, if we're adding it
This way, the code loop is exited when your user manually exits the loop (or if they've entered too many calories). Now, your user should be able to input caloric data and have it added up for them.
Also, I would remove the counter because the counter isn't necessary for this loop. We've got a few reasons why we don't need the counter:
The counter isn't directly affecting the loop (e.g. no while counter < 5)
We have the computer asking for user input, so the program stops and gives control to the human thus no infinite loop
We have break statements to remove us from the (new) loop

How to pass arguments to function, differently different times?

I need to pass two different arguments to the code (cartype and bonus) and set a for loop, so that each time it loops a different kind of car would be displayed & a different bonus amount.
I have looked for several solutions on here, on google & in my textbook without any success. I know it would be easier to do them all seprately but this is what is required.
Any help would be fantasic :) Please find part of my code below.
def main():
#This program uses a while loop, to give the user the option to go again.
while True:
#This displays the heading & instructions.
print ('AUSSIE BEST CAR INCOME AND BONUS CALCULATOR')
print ('*********************************')
print('**Please input data in the following format: 10000 **')
print('**Please be aware that inputs of zero(0) are invalid**')
#The program asks the user to input the total price of the cars, one by one.
kluger_price = float(input('Please enter the selling price of the Toyota Kluger: $'))
patrol_price = float(input('Please enter the selling price of the Nissan Patrol: $'))
territory_price = float(input('Please enter the selling price of the Ford Territory: $'))
#The program asks the user to input the total amount of cars sold, one by one.
kluger_sold = int(input('Please enter the number of Toyota Klugers sold in 2014:'))
patrol_sold = int(input('Please enter the number of Nissan Patrols sold in 2014:'))
territory_sold = int(input('Please enter the number of Ford Territorys sold in 2014:'))
#The program calculates the totals of each of the cars, one by one.
kluger_total = kluger_price*kluger_sold
patrol_total = patrol_price*patrol_sold
territory_total = territory_price*territory_sold
total = kluger_total + patrol_total + territory_total
#The program calculates the total bonus
if total <= 500000:
bonus = 0.001*total
elif total <= 1000000:
bonus = 500 + (total - 500000)*0.002
elif total <= 5000000:
bonus = 1500 + (total -1000000)*0.003
elif total <= 10000000:
bonus = 13500 + (total - 5000000)*0.004
else:
bonus = 33500 + (total - 10000000)*0.005
#The program calculates the bonus contributed by each car
global kluger_bonus
kluger_bonus = kluger_total/total*bonus
global patrol_bonus
patrol_bonus = patrol_total/total*bonus
global territory_bonus
territory_bonus = territory_total/total*bonus
print ('*********************************')
#The program displays the total income made and bonus
print ('The amount made from the Toyota Klugers is $', format(kluger_total,',.2f'))
print ('The amount made from the Nissan Patrols is $', format(patrol_total,',.2f'))
print ('The amount made from the Ford Territorys is $', format(territory_total,',.2f'))
print ('The total amount amount made from all three cars is $', format(total,',.2f'))
print ('The total bonus for 2014 is $', format(bonus,',.2f'))
print ('The bonus contributed through the sale of the Toyota Klugers is $', format(kluger_bonus,',.2f'))
print ('The bonus contributed through the sale of the Nisssan Patrols is $', format(patrol_bonus,',.2f'))
print ('The bonus contributed through the sale of the Ford Territorys is $', format(territory_bonus,',.2f'))
cartype = ['Toyota Kluger', 'Nissan Patrol', 'Ford Territory']
bonus = [kluger_bonus, patrol_bonus, territory_bonus]
[CalculateAdditionalBonus(cartype, bonus) for cartype, bonus in enumerate(3)]
def CalculateAdditionalBonus(cartype,bonus):
rate = input('Please input the value the assessed for the additional bonus of the', cartype')
additional_bonus = rate*bonus
print('The additional bonus for the', cartype' is $', format(additional_bonus,',.2f')
def CalculateTotalBonus():
#This ends the while loop, giving the user the option to go again.
try_again = int(input('This is the end of the calculations.Press 1 to try again, 0 to exit.'))
if try_again == 0:
break
if try_again == 1:
print('===============================================================')
main()
I'm not sure if I understood your question correctly, but I guess you want to pass cartype and bonus into your CalculateAdditionalBonus function. If that's the case, just zip the two lists to combine them into a list of tuples, then iteratively feed into your function.
cartype = ['Toyota Kluger', 'Nissan Patrol', 'Ford Territory']
bonus = [kluger_bonus, patrol_bonus, territory_bonus]
[CalculateAdditionalBonus(cartype, bonus) for cartype, bonus in zip(cartype, bonus)]
The answer is to use an if-elif-else statement.

Categories