Python If Elif Else conditions - python

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:

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: ")

Recurring line disappearance, issue with while loop

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

H3lp High School Student With Python Loop

This is supposed to be code for a system in a store that loops again and again if someone wants to buy something else. Please help.
menu=["apple","water","juice"]
apple=50
water=80
juice=100
money=int(input("How much money in pennies do you have?"))
if money>=100:
print("We have the following items you can buy: apple, water, juice")
elif money>=80 and money<=100:
print("We have the following items you can buy: apple, water")
elif money>=50 and money<=80:
print("We have the following item you can buy: apple")
else:
print("Sorry, you can't buy anything.")
buy=input("What do you want to buy?")
if buy=="apple":
print("You have",money-50)
elif buy=="water":
print("You have",money-80)
else:
print("You have",money-100)
other=(input("Do you want to buy anything else?"))
if other=="yes":
while x=0:
print(x)
continue
elif other=="no":
x+1
else:
print("Error")
The last part doesn't work- can someone fix it so it does? This is Python 3- thanks.
problem fixed & loop optimized -
the problem you encountered was the extra brackets () around your input-function.
the loop is now optimized because your whole buying cycle is now inside this while True: loop. it will be repeated again and again until the user inputs something different then "yes" at the other question.
while True:
menu=["apple","water","juice"]
apple=50
water=80
juice=100
money=int(input("How much money in pennies do you have?"))
if money>=100:
print("We have the following items you can buy: apple, water, juice")
elif money>=80 and money<=100:
print("We have the following items you can buy: apple, water")
elif money>=50 and money<=80:
print("We have the following item you can buy: apple")
else:
print("Sorry, you can't buy anything.")
buy=input("What do you want to buy?")
if buy=="apple":
print("You have",money-50)
elif buy=="water":
print("You have",money-80)
else:
print("You have",money-100)
other=input("Do you want to buy anything else?")
if other=="yes":
continue
else:
break
other=(input("Do you want to buy anything else?"))
if other=="yes":
while x=0: <-- should use x==0, but x is not declared
print(x) <-- wrong indentation
continue
elif other=="no":
x+1 <-- even if x was declared, this only sum and nothing
else: more (nothing changes in your program)
print("Error")
This last part basically does nothing useful even if it worked. I suggest you to use the code posted in the other answer.

Why cant i get the total from a While true loop

I cant seem to get the total from my while true loop. I am trying to write a code . That will get the total value for all the seats a waiter enters. But I keep getting the total like this Total:$ q I had set q to break if the user input it for a seats. Can you help me please. Here is my syntax.
while True:
seats = raw_input("Enter the value of the seat [q to quit]:")
if seats == 'q':
break
print "Total: $", seats
total = 0
while True:
seats = raw_input("Enter the value of the seat [q to quit]:")
if seats == 'q':
break
total += int(seats)
print "Total: $", str(total)
If you want it to show the total after each loop just push the print statement inside the loop.
You need to sum variable seats with your input value, not reassigning value.
You were wrong in choosing operator, you need to use +=, not =.
Replace your code with this:
while True:
input = raw_input("Enter the value of the seat [q to quit]:")
if input == 'q':
break
seats += input
print "Total: $", seats
After that, read this question and answers:
What exactly does += do in python?

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

Categories