Homework: Sales Tax python program - python

I'm working on a homework problem in Python. I'm trying to create a program that calculates sales tax. I need to give the user an option to set the beginning rate to calculate and an ending rate to calculate. The program will then calculate all whole numbers between begin and end (ex. begin =5%, end = 8% it would calculate 5,6,7,8 % tax.
I've been asked to use this code:
while begin <= 0 or begin > 10:
begin = int(input("Enter tax rate: "))
I also have to use a for loop.
I have to give the user 3 prompts: sales price, beginning rate, ending rate. The program will then give the user a table of rates and total prices:
I'm stumped at the for loop and incorporating the while statement
I'm at a very beginning process of:
productprice = float(input("Enter the product price: "))
begin = float(input("Enter tax rate: "))
total = productprice + productprice * begin/100
print total
raw_input ("Enter to exit")

Like this?
price = float(input("Enter the product price: "))
# declare begin and end variables as empty strings to start
begin = ""
end = ""
# the while loops are to make sure the user inputs a tax rate that
# is more than 0 and less than 10
while begin <= 0 or begin > 10:
begin = int(input("Enter tax rate: "))
while end <= 0 or end > 10:
end = int(input("Enter end tax rate: "))
# does the math for every integer between beginning and end, prints a 'table'
for x in range(begin,end+1):
total = price + price * x/100
print "Price: "+str(price)+"\tTax: "+str(x)+"\tTotal: "+str(total)
x += 1
raw_input ("Enter to exit")
Output:
Enter the product price: 100
Enter tax rate: 6
Enter end tax rate: 9
Price: 100.0 Tax: 6 Total: 106.0
Price: 100.0 Tax: 7 Total: 107.0
Price: 100.0 Tax: 8 Total: 108.0
Price: 100.0 Tax: 9 Total: 109.0
Enter to exit

Related

Minimum number and interest does not print correctly

I am in a Python class and a few weeks ago we were given these sets of instructions for an assignment:
Write a program that utilizes a loop to read a set of five floating-point
values from user input. Ask the user to enter the values, then print the
following data:
Total,
Average,
Maximum,
Minimum,
Interest at 20% for each original value entered by the user.
Use the formula: Interest_Value = Original_value + Original_value*0.2
I uploaded a different assignment for the class, but this problem is driving me crazy because I cannot figure out why minimum number, and interest does not work correctly. Any suggestions would be appreciated. Thank you.
This is the code I wrote. My problem is the minimum number does not output and the printed interest is wrong.
entered_number = 0
sum = 0
average = 0
max_number = 0
min_number = 0
interest = 0.2
for entered_number in range(5):
entered_number = float(input('Enter a number: '))
if entered_number > max_number:
max_number = entered_number
if entered_number < min_number:
min_number = entered_number
sum = sum + entered_number
average = sum / 5
interest = entered_number + (entered_number * interest) # removing the () didn't solve
print('Total:', sum)
print('Average:', average)
print('Maximum number:', max_number)
print('Minimum number:', min_number)
print('Interest at 20% for each entered number is: ', interest)
My output example:
Enter a number: 20
Enter a number: 30
Enter a number: 40
Enter a number: 50
Enter a number: 60
Total: 200.0
Average: 40.0
Maximum number: 60.0
Minimum number: 0
Interest at 20% for each entered number is: 90123060.0
Try setting your min_number and max_number values to positive and negative infinity respectively, upon intialization.
Then for the interest it sounds like you need to collect multiple values and output all of them if I understand correctly. And you don't want to overwrite the interest variable because that is constant between all numbers so use current_interest and move it inside the loop.
For the total you shouldn't use sum as a variable name since it overwrites the function. instead use total, and move it inside the loop so that the value updates for each input received.
import math
entered_number = 0
total = 0
average = 0
max_number = -math.inf
min_number = math.inf
interest = 0.2
interest_list = []
for entered_number in range(5):
entered_number = float(input('Enter a number: '))
if entered_number > max_number:
max_number = entered_number
if entered_number < min_number:
min_number = entered_number
current_interest = entered_number + (entered_number * interest)
interest_list.append(current_interest) # collect all interest values
total += entered_number # dont use sum as a variable name
average = total / 5
print('Total:', total)
print('Average:', average)
print('Maximum number:', max_number)
print('Minimum number:', min_number)
print('Interest at 20% for each entered number is: ', interest_list)
OUTPUT
Enter a number: 20
Enter a number: 30
Enter a number: 40
Enter a number: 50
Enter a number: 60
Total: 200.0
Average: 40.0
Maximum number: 60.0
Minimum number: 20.0
Interest at 20% for each entered number is: [24.0, 36.0, 48.0, 60.0, 72.0]

Expensive Calculation Program Operand Confusion

What i'm trying to do is have an initial input take a number, then proceed to take numbers that are entered afterwards until the loop is closed by entering 0. The output should be the Initial input, the amount entered added up, then subtracted from the Initial number.
I want to change the overall structure of the program as little as possible.
budget = float(input('Enter amount budgeted for the month: '))
spent = 0
total = 0
while spent >= 0:
spent = float(input('Enter an amount spent(0 to quit): '))
total += spent
print ('Budgeted: $', format(budget, '.2f'))
print ('Spent: $', format(total, '.2f'))
if budget > total:
difference = budget - total
print ('You are $', format(difference, '.2f'), \
'under budget. WELL DONE!')
elif budget < total:
difference = total - budget
print ('You are $', format(difference, '.2f'), \
'over budget. PLAN BETTER NEXT TIME!')
elif budget == total:
print ('Spending matches budget. GOOD PLANNING!')
First, you need to loop until user enters 0. You can use a loop that breaks on 0:
while True:
spent = float(input('Enter an amount spent(0 to quit): '))
if spent == 0: break
total += spent
Or loop until spent is 0. This means initializing it to some non-zero value.
spent = -1
while spent != 0:
spent = float(input('Enter an amount spent(0 to quit): '))
total += spent
Also, all the other code should be outside the loop:
budget = float(input('Enter amount budgeted for the month: '))
spent = -1
total = 0
while spent != 0:
spent = float(input('Enter an amount spent(0 to quit): '))
total += spent
print ('Budgeted: $', format(budget, '.2f'))
print ('Spent: $', format(total, '.2f'))
if budget > total:
difference = budget - total
print ('You are $', format(difference, '.2f'), \
'under budget. WELL DONE!')
elif budget < total:
difference = total - budget
print ('You are $', format(difference, '.2f'), \
'over budget. PLAN BETTER NEXT TIME!')
else:
print ('Spending matches budget. GOOD PLANNING!')

How to introduce a while loop in order to calculate monthly interest rate?

I have a question where im asked to calculate interest rate of an account after asking user for:
P is the present value of the account.
i is the monthly interest rate.
t is the number of months.
The current code I have is this:
def get_value(p, i , t):
return p * (1 + i) ** t
def main():
p = float(input("Please enter the current amount of money in your account: "))
i = float(input("Please enter the monthly interest rate: "))
t = float(input("Please enter the number of months: "))
#the while loop would probably go here, but I just dont know how to do it#
future_total = get_value(p, i, t)
print ("\nAfter", t, "months, you will have $", format(future_total, ".2f"), "in your account.")
main()
But the output is only giving me the final amount after 10 months, how do I implement a loop in order to see how much money would be in the account since month 1?
I would first make a variable called month and set it equal to 1. Then I would use the while loop so that when the month is less than the inputted month, the present value will be updated based on the inputted information. This will print out the money in the account for each month and not just the final value.
def get_value(p, i , t):
month = 1
while month <= t:
p = p * (1 + i)
print(month, p)
month += 1
def main():
p = float(input("Please enter the current amount of money in your account: "))
i = float(input("Please enter the monthly interest rate: "))
t = float(input("Please enter the number of months: "))
print(get_value(p,i,t))
# future_total = get_value(p, i, t)
# print ("\nAfter", t, "months, you will have $", format(future_total, ".2f"), "in your account.")
# print(f'After {t} months, you will have ${future_total} in your account.')
main()

How do I make this code loop into dictionaries and not continue looping in python?

Write a program to calculate the cost of dinner
If the person is under 5, dinner is free
If the person is under 10, dinner is $5
If the person is under 18, dinner is $10
If the person is over 65, the dinner is $12
All other dinners pay $15
Calculate 8% tax
Display the total for each diner, the number of diners, the average cost per diner, and the cumulative total for all diners
Program should loop until exit is entered, with each loop a new diner is added and the total overall numbers updated
Is what I need to do. I'm not sure how to do it so the totals go into dictionaries and not loop.
I've done a similar question, but now this one needs to have the amounts added all together and I'm not sure how. This is the code I've done for a previous similar question. The problem I seem to be currently having i it wont go into the dictionary and there for wont print it at the end. I also need it to keep looping until I type quit.
dinner = {}
total ={}
name = input("What's your name? ")
age = input("What age is the person eating? ")
age = int(age)
amount = input("How many people that age? ")
amount = int(amount)
while True:
if name == 'quit':
print('Done')
break
elif age < 5:
price = 0 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age < 10:
price = 5 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age < 18:
price = 10 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age > 65:
price = 12 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
else:
price = 15 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
print("Thank you for having dinner with us! \nYour total is {total}, for {dinner}.")
The most succinct way to accomplish this is to bin the ages, determine which bin a given age falls into, and then use the index to return the price.
np.digitize accomplishes that task
the parameter bins, contains the ages, and determines which index in the list, a given value fits into. bins is exclusive, therefore the ranges are 0-4, 5-9, 10-17, 18-65 and 66+.
the ranges correspond to index 0, 1, 2, 3, and 4.
idx is used to return the corresponding price per age range
Use a function to return the cost, instead of a bunch of if-elif statements
The directions in yellow, don't require the name or the age of the person to be returned.
Everything required to print at the end, can be calculated from maintaining a list of cost, containing the price of each customer.
print(f'some string {}') is an f-String
Type Hints are used in functions (e.g. def calc_cost(value: int) -> float:).
import numpy as np
def calc_cost(value: int) -> float:
prices = [0, 5, 10, 15, 12]
idx = np.digitize(value, bins=[5, 10, 18, 66])
return prices[idx] + prices[idx] * 0.08
cost = list()
while True:
age = input('What is your age? ')
if age == 'exit':
break
cost.append(calc_cost(int(age)))
# if cost is an empty list, nothing prints
if cost:
print(f'The cost for each diner was: {cost}')
print(f'There were {len(cost)} diners.')
print(f'The average cost per diner was: {sum(cost)/len(cost):.02f}')
print(f'The total meal cost: {sum(cost):.02f}')
Output:
What is your age? 4
What is your age? 5
What is your age? 9
What is your age? 10
What is your age? 17
What is your age? 18
What is your age? 65
What is your age? 66
What is your age? exit
The cost for each diner was: [0.0, 5.4, 5.4, 10.8, 10.8, 16.2, 16.2, 12.96]
There were 8 diners.
The average cost per diner was: 9.72
The total meal cost: 77.76
If not allowed to use numpy:
def calc_cost(value: int) -> float
return value + value * 0.08
cost = list()
while True:
age = input("What age is the person eating? ")
if age == 'exit':
break
age = int(age)
if age < 5:
value = 0
elif age < 10:
value = 5
elif age < 18:
value = 10
elif age < 66:
value = 15
else:
value = 12
cost.append(calc_cost(value))
if cost:
print(f'The cost for each diner was: {cost}')
print(f'There were {len(cost)} diners.')
print(f'The average cost per diner was: {sum(cost)/len(cost):.02f}')
print(f'The total meal cost: {sum(cost):.02f}')
Notes:
Don't use break in all the if-elif conditions, because that breaks the while-loop
Anytime you're repeating something, like calculating price, write a function.
Familiarize yourself with python data structures, like list and dict
this one needs to have the amounts added all together and I'm not sure how.
list.append(price) in the loop
sum(list) to get the total

Python: How can I store multiple user inputs when using for loop?

I am trying to recreate a problem from our classwork: Write a program that can handle a shopping event. First, it requests the number of items bought, then asks for each items' price and tax rate. Then prints the total cost.
Example:
How many items you bought: 2
For item 1
Enter the price: 10
Enter the tax rate: 0
For item 2
Enter the price: 20
Enter the tax rate: 8
Your total price is 31.6
I have no knowledge on how I would compute for items larger than 1. ie my code works for 1 item.
items = int(input("How many items did you buy? "))
for i in range(1, items+1, 1):
print("For item ",i)
price = float(input("Enter the price: "))
tax_rate = float(input("Enter the tax rate: "))
total = price + price*(tax_rate/100)
print("Your total price is", total)
I need to somehow save the totals after each iteration and add them all up. I am stumped.
Note: This is an introduction to python course and also my first programming course. We've only learned for loops thus far.
You need to have an initialized counter to have a running total.
items = int(input("How many items did you buy? "))
total = 0
for i in range(1, items+1, 1):
print("For item ",i)
price = float(input("Enter the price: "))
tax_rate = float(input("Enter the tax rate: "))
total += price + price*(tax_rate/100)
print("Your total price is", total)

Categories

Resources