I was wondering if anyone could help point me in the right direction! I'm a beginner and I'm totally lost. I'm trying to make a Sentinel controlled loop that asks the user to "enter the amount of check" and then ask "how many patrons for this check". After it asks the user then enters it until they type -1.
once user is done inputting it is suppose to calculate the total,tip,tax of each check with an 18% tip for anything under 8 patrons and 20%tip for anything over 9 and a tax rate of 8%.
and then it should add up the Grand totals.
ex: check 1 = 100$
check 2 = 300
check 3 = 20
Total checks = $420
I'm not asking for someone to do it for me but just if you could point me in the right direction, this is all i have so far and im stuck.
As of right now the code is horrible and doesn't really work.
I completed it in Raptor and it worked perfectly I just don't know how to convert it to python
sum1 = 0
sum2 = 0
sum3 = 0
sum4 = 0
sum5 = 0
check = 0
print ("Enter -1 when you are done")
check = int(input('Enter the amount of the check:'))
while check !=(-1):
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
tip = 0
tax = 0
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
total = check + tax + tip
sum1 = sum1 + check
sum2 = sum2 + tip
sum3 = sum3 + patron
sum4 = sum4 + tax
sum5 = sum5 + total
print ("Grand totals:")
print ("Total input check = $" + str(sum1))
print ("Total number of patrons = " + str(sum3))
print ("Total Tip = $" +str(sum2))
print ("Total Tax = $" +str(sum4))
print ("Total Bill = $" +str(sum5))
Your code runs fine, but you have some logic problems.
It appears you're planning to deal with multiple checks at the same time. You'll probably want to use a list for that, and append checks and patrons to it until check is -1 (and don't append the last set of values!).
I think the real issue you're having is that to leave the loop, check must be equal to -1.
If you follow that a bit further down, you continue to work with check, which we now know is -1, regardless of what happened previously in the loop (check is overwritten every time).
When you get to these lines, then you have a real problem:
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
# This is the same, we know check == -1
if patron <= 8:
tip = (-1 * .18)
elif patron >= 9:
tip = (-1 * .20)
At this point you probably won't be able to do anything interesting with your program.
EDIT: A bit more help
Here's an example of what I'm talking about with appending to a list:
checks = []
while True:
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
# here's our sentinal
if check == -1:
break
checks.append((patron, check))
print(checks)
# do something interesting with checks...
EDIT: Dealing with cents
Right now you're parsing input as int's. That's OK, except that an input of "3.10" will be truncated to 3. Probably not what you want.
Float's could be a solution, but can bring in other problems. I'd suggest dealing with cents internally. You might assume the input string is in $ (or € or whatever). To get cents, just multiply by 100 ($3.00 == 300¢). Then internally you can continue to work with ints.
This program should get you started. If you need help, definitely use the comments below the answer.
def main():
amounts, patrons = [], []
print('Enter a negative number when you are done.')
while True:
amount = get_int('Enter the amount of the check: ')
if amount < 0:
break
amounts.append(amount)
patrons.append(get_int('Enter the number of patrons: '))
tips, taxs = [], []
for count, (amount, patron) in enumerate(zip(amounts, patrons), 1):
tips.append(amount * (.20 if patron > 8 else .18))
taxs.append(amount * .08)
print('Event', count)
print('=' * 40)
print(' Amount:', amount)
print(' Patron:', patron)
print(' Tip: ', tips[-1])
print(' Tax: ', taxs[-1])
print()
print('Grand Totals:')
print(' Total amount:', sum(amounts))
print(' Total patron:', sum(patrons))
print(' Total tip: ', sum(tips))
print(' Total tax: ', sum(taxs))
print(' Total bill: ', sum(amounts + tips + taxs))
def get_int(prompt):
while True:
try:
return int(input(prompt))
except (ValueError, EOFError):
print('Please enter a number.')
if __name__ == '__main__':
main()
Related
im making a food ordering system but im having trouble with multiple order of the same item but in different sizes. I have put "fs,fm,fl" with a value of 0 so that it would be my basis as a counter for each sizes of my fries, i also have used "total" to add up every value of each sizes. After i put "2" large fries and "2" medium fries, My "total" and "fs+fm,+fl" is different from each other.
i expected my total and the added value to be the same but they are different. Is there an error with my computation? Is there any alternative/faster way to calculate the total value of different sizes? here is my code (it is unfinished)
food = ["Burger", "Fries", "Hotdog", "Sundae", "Coke Float"]
cart = []
cost = []
total = 0
fs = 0
fm = 0
fl = 0
def menu():
print(f"\t\t\t\t{'MENU'}")
collection = [["\nCode", " Description", " Size", " Price"],
[" 2", " Fries", " S/M/L", " 20/35/50"]]
for a in collection:
for b in a:
print(b, end=' ')
print()
menu()
first = True
def ordering():
print("\nPlease select the CODE of the food you want to order")
while first == True:
global total
global fs
global fm
global fl
order = input("Type the code you want to order: \n")
#fries
if order == ("2"):
print("You have selected \n")
print("\n", food[1], "\n")
size = input("What size do you want? S/M/L: ")
if size == "s" or size == "S":
cart.append(food[1])
i = int(input("Enter quantity:"))
total = total + 20
total = total * i
fs = i * 20
print(fs)
elif size == "M" or size == "m":
cart.append(food[1])
i = int(input("Enter quantity:"))
total = total + 35
total = total * i
fm = i * 35
print(fm)
elif size == "l" or size == 'L':
cart.append(food[1])
i = int(input("Enter quantity:"))
total = total + 50
total = total * i
fl = i * 50
print(fl)
else:
print("Invalid size")
#cart.append(food[1])
#cost.append(price[1])
try_again = input("\nWould you like to add more? (Y/N):").lower()
if try_again != ("y"):
break
else:
print("\nInvalid input. Please put only the CODE of the item\n")
ordering()
def inside_cart():
while first == True:
print(' ')
print(' ')
print("The inside of your cart are currently:")
print(cart)
print(fs + fm + fl,total)
suggestion = input("would you like to order more? Y/N: ").lower()
if suggestion.lower() == "y":
ordering()
print("\nOkay, proceeding to payment....\n")
break
inside_cart()
I think the error originates in the price calculations:
total = total + 20
total = total * i
fs = i * 20
If you order two small fries this works fine the first time, as total becomes 20 and then 40 to account for it being two items. However, once you order the large fries you first add 50 for a total price of 90, and then multiply it by two for a price of 180, which should be 140.
To fix this, just change the total calculation to this:
total += i * price
Now you will add to the total only the price of the items ordered. As a rule of thumb, you should probably not multiply an accumulated value unless you're sure that's what needs to be done.
For the fs/fm/fl there seems to be an issue present too, as doing multiple orders for the same size will make the value stored in the variable only count the price of the last order of this size. If you for instance ordered small fries and then 1 small fries, fs would only be 20 when it should be 100. To fix that, you can apply an analogous change:
fs += i * 20
So make sure next time that each calculation is done separately, and try to imagine when some orders have already been done, how it would affect the values you are trying to calculate next.
On a different note, you may want to work on creating a table of sorts to store the different prices for items and sizes, as this code will quickly grow out of control for more items and be a nightmare to maintain.
Hope this helps!
for i in range (0, 3):
print() # When iterates creates a space from last section
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
penalty = (days_late * 5)
final_mark = (raw_mark - penalty)
# Selection for validation
if 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark >= 40:
print("Student ID:", str(student_id[i]))
print() # Spacing for user readability
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("This means that the result is now:", final_mark,"(this was not a capped mark)")
elif 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark < 40: # Final mark was below 40 so mark must be capped
print("Student ID:", str(student_id[i]))
print()
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("Therefore, as your final mark has dipped below 40, we have capped your grade at 40 marks.")
else:
print("Error, please try again with applicable values")
At the else i would like the loop to loop back through but not having iterated i to the next value, so that it can be infinite until all 3 valid inputs are entered... cannot use a while loop nor can i put the if - elif- else outside the loop. Nor can i use a function :(
You can have your for loop behave like a while loop and have it run forever and implement your i as a counter. Then the loop can be terminated only if it ever hits 3 (or 2 so that you indices dont change), while otherwise it is set back to 0:
cnt_i = -1
for _ in iter(int, 1):
cnt_i += 1
if ...
else:
cnt_i = 0
if cnt_i == 2:
break
But seriously, whatever the reason for not using a while loop, you should use it anyhow..
Try something like this. You can keep track of the number of valid inputs, and only stop your loop (the while) once you hit your target number.
valid_inputs = 0
while valid_inputs <= 3:
...
if ...:
...
elif ...:
...
else:
# Immediately reset to the top of the while loop
# Does not increment valid_inputs
continue
valid_inputs += 1
If you really cannot use a while loop...
def get_valid_input():
user_input = input(...)
valid = True
if (...): # Do your validation here
valid = False
if valid:
return user_input
else:
return get_valid_input()
for i in range (0, 3):
input = get_valid_input()
# Do what you need to do, basically your program from the question
...
...
There are some additional gotchas here, as in you need to worry about the possibility of hitting the maximum recursion limit if you keep getting bad input values, but get_valid_input should ideally only return when you are sure you have something that is valid.
You can put the input statement inside while loop containing try block.
for j in range(3): # or any other range
try:
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
break
except:
pass
I have a school project for making a betting programme. It asks for the account balance and checks if the user can play more or tells them to stop if they are broke. I do not know how to add a while loop that checks if they have enough money to play again and asks them if they want to play again.
The code is below:
import random
for x in range (1):
x=random.randint(1,31)
point=int(0)
savings = int(input("Enter your total amount of money you have in your bank account"))
betmoney = int(input("Enter the money you are betting"))
num = int(input("Enter a number between 1 and 30"))
bef = (savings - betmoney)
if num == x:
print ("you have guessed the mystery number well done. Your earnings just got multiplied by 6")
point = point + 6
import random
for x in range (1):
x=random.randint(1,31)
if num % 2 == 0:
print("since your number is even, you get double your money back")
point = point + 2
else:
point = point + 0
if num % 10 == 0:
print("since your number is a multiple of 10 you get 3x your money back")
point = point + 3
else:
point = point + 0
for i in range(2,num):
if (num % i) == 0:
point = point +0
break
else:
print(num,"is a prime number so you will get 5x your money back")
point = point + 5
if num < 5:
print("since your number is lower than 5 you get double your money back")
point = point + 2
else:
point = point + 0
else:
print("unfortunatley you have nor guessed the right mystery number. better luck next time.")
win = (point * betmoney)
aft = (bef + win)
print ("Your bank account after playing is now" , aft)
print ("You have won" , win)
print ("btw the mystery number was" , x)
I added a while loop and i came up with this.
The following is the code:
import random
point = int(0)
savings = int(input("Enter your total amount of money you have in your bank account : "))
play = bool(True)
while savings > 0 and play:
for x in range (1):
x = random.randint(0, 30)
betmoney = int(input("Enter the money you are betting : "))
if savings >= betmoney:
savings = savings - betmoney
else:
print("Please enter an amount less than ", savings)
continue
num = int(input("Enter a number between 1 and 30 : "))
if num == x:
print("you have guessed the mystery number well done. Your earnings just got multiplied by 6")
point = point + 6
import random
for x in range (1):
x = random.randint(1, 31)
if num % 2 == 0:
print("since your number is even, you get double your money back")
point = point + 2
else:
point = point + 0
if num % 10 == 0:
print("since your number is a multiple of 10 you get 3x your money back")
point = point + 3
else:
point = point + 0
for i in range(2,num):
if (num % i) == 0:
point = point +0
break
else:
print(num,"is a prime number so you will get 5x your money back")
point = point + 5
if num < 5:
print("since your number is lower than 5 you get double your money back")
point = point + 2
else:
point = point + 0
else:
print("unfortunatley you have nor guessed the right mystery number. better luck next time.")
win = (point * betmoney)
aft = (savings + win)
print("Your bank account after playing is now", aft)
print("You have won", win)
print("The mystery number was" , x)
if savings > 0:
play = bool(input("Do you want to play again (Y/N)? "))
print("You have no more money left. You are broke. Thanks for playing though!")
If you are using an if statement, you could try something by setting a stopping point for the amount of money you need to play (e.g. you must have $1,000 to play).
For now, let's assume that you need $1000 dollars to play, and we'll call that in your already present variable aft. The code would be something along the following:
while aft > 1,000:
#confirms that the user can play
print("You can play! Have fun!")
#(Enter your current code here)
if aft <1,000:
print("Sorry, but your current value of " + aft + "is not enough to play. Please earn more money.")
exit()
I'm very new to programming and I've encountered a problem with a basic guessing game I've been writing.
x is a random number generated by the computer. The program is supposed to compare the absolute value of (previous_guess - x) and the new guess minus x and tell the user if their new guess is closer or further away.
But the variable previous_guess isn't updating with the new value.
Any help would be appreciated.
Here is the code so far:
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
while True:
previous_guess = 0 # Should update with old guess to be compared with new guess
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Your previous guess is being reinitialized every time you loop. This is a very common error in programming so it's not just you!
Change it to:
previous_guess = 0
while True:
#Rest of code follows
Things you should be thinking about when stuff like this shows up.
Where is your variable declared?
Where is your variable initialized?
Where is your variable being used?
If you are unfamiliar with those terms it's okay! Look em up! As a programmer you HAVE to get good at googling or searching documentation (or asking things on stack overflow, which it would appear you have figured out).
Something else that is critical to coding things that work is learning how to debug.
Google "python debug tutorial", find one that makes sense (make sure that you can actually follow the tutorial) and off you go.
You're resetting previous_guess to 0 every time the loop begins again, hence throwing away the actual previous guess. Instead, you want:
previous_guess = 0
while True:
guess = ....
You need to initialize previous guess before while loop. Otherwise it will be initialized again and again.
You have updated previous guess in multiple places. You can make it simpler:
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = 0 # Should update with old guess to be compared with new guess
while True:
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
print("Getting warmer...")
else:
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
previous_guess = guess #####
You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this:
Add before while { previous_guess = x }
Add After While { previous_guess += x }
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = x
while True:
# Should update with old guess to be compared with new guess
previous_guess += x
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Picture When u win
Picture When u loose
I want to create a while loop to prompt the user if they would like to enter a living cost. The user would input 'y' for yes and the loop would proceed.
I this loop I would like to add up all the living expense entered and once the loop ends to store to the total amount in total_living.
Example would be
l_cost = input('Enter living cost? y or n ')
while l_cost != 'n' (loop for living cost)
totat_living = (keeps adding until I say all done
l_cost = input('Enter living cost? y or n ')
Other while and for loops for different scenarios
total_exp = total_living + total_credit + total_debt ect ect
I just need a little help with this as to how to add up multiple values and then maintaining the total value for the loop that I am in.
If someone could point me to an example of a function or loop that is similar or tell me where to look that would be great!
You may try using while as below:
flag = input ("wish to enter cost; y or n" )
total=0
While flag != 'n':.
cost = int(input ("enter cost: "))
total = total + cost
flag = input("more ?? Y or n")
print(total)
total_cost = 0.0
prompt = 'Enter a living cost? y or n: '
answer = input(prompt)
while answer.lower() != 'n':
cost = input('Enter your cost: ')
total_cost = total_cost + float(cost)
answer = input(prompt)
print('Total cost is $' + str(total_cost))
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
Note
Try to convert this example to your problem.