Correct Change python program - python-3.x

I am supposed to
Design and write a Python program that gives exact change for an item purchased with $5 or less. Use a float data type to represent money (You may want to multiply this number by 100 so that you get an integer for your calculation, such that $5.00 represents 500 cents, $2.35 represents 235 cents, etc.)
Below is my code:
amount = float(input('Enter item cost: '))
tender = float(input('Enter amount tendered: '))
change = int((tender - amount)*100)
dollars = change // 100
change = change % 100
quarters = change // 25
change = change % 25
dimes = change // 10
change = change % 10
nickels = change // 5
change = change % 5
pennies = change
#output
print('Dollar bills:', dollars)
print('Quarters:', quarters)
print('Dimes:', dimes)
print('Nickels:', nickels)
print('Pennies:', pennies)
An expected output for an item that costs $2.71 when the amount tendered is $5.00, would be:
Dollars: 2
Quarters: 0
Dimes: 2
Nickels:1
Pennies:4
but my output is giving me:
Enter item cost: 2.71
Enter amount tendered: 5.00
Dollars: 2
Quarters: 1
Dimes: 0
Nickels: 0
Pennies: 4
What am I doing wrong? Any help would be appreciated
Thanks!

Related

How do I assign a value to a word?

I'm creating a calculating list for the user to select from such as: pepsi, sprite, coke
and after user selects their fav drink, it will calculate: the calories(they all have diff. calories) + plus how many they drink per week + per year and then Print how many total calories they consume per year.
I got the math part down but I can't figure out how to add the "drink" they select into the final output.
EXAMPLE:
pepsi 100
sprite 200
coke 300
So, if they select pepsi, it should then take variable pepsi, then add how many per day + week + year then print total calories for year. Make sense?
right now it just prints the same number for any selection. when clearly the calories will vary.
Here is how I tried coding it:
cans_per_day = int(input("\nHow many cans per day?\n"))
sodas_per_week = int(input("How many cans do you drink per week?\n"))
drink_of_choice = input("What's your drink of choice?\n\n" + "Pepsi\nWild Cherry Coke\nOrange Fanta\nMountain Dew\nMello Yello\nSprite\n\n")
drink_of_choice = input + 41 * cans_per_day * sodas_per_week * 4 * 12 / (453.592)
print(drink_of_choice)
You can just check which drink is selected with something like this (if you use python):
if drink == "pepsi":
calories = 100
elif drink == "sprite":
calories = 200
elif drink == "coke":
calories = 300
then you can just multiply with calories in your calculation

Format the total so it does not show decimal places

So, I'm trying to make this code not show any decimal places in the end (total)... But I can't really find a way to do it. Is there a way to do it without having to rewrite everything?
test1_weight = float(input("Type your 1st Test weight: "))
test2_grade = float(input("Type your 1st Test grade: "))
test2_weight = float(input("Type your 1st Test weight: "))
total = (test1_grade * test1_weight + test2_grade * test2_weight)/(test1_weight + test2_weight)
print ("The weighted average is: ", total)
You can cast total to an integer:
total = int(total)
For example:
total = 3.75
total = int(total)
print(total) # 3
Since each of your inputs are floats, your 'total' will also be a float. If you want the 'total' to not have any decimal points, you should cast total to an integer before printing: int(total)
You can also round the result with the round function
Exemple:
round(total)
You can accomplish this with f-strings. F-strings allow you to interpolate python expressions with strings, meaning you can stick your variable right in there:
>>> total = 3.75
>>> print(f"The total is: {total}")
The total is: 3.75
It also allows for formatting syntax, which means we can restrict the float to no decimal places by specifying the float format .0f after a colon.
>>> total = 3.75
>>> print(f"The total is: {total:.0f}")
The total is: 4

How to calculate the annual rate in python 3

Here's the code:
P = int(input("Enter starting principle please.\n"))
n = int(input("Enter Compound interest rate.(daily, monthly, quarterly,half-year, yearly)\n"))
r = float(input("Enter annual interest amount. (decimal)\n"))
t = int(input("Enter the amount of years.\n"))
t = 1
while t-1 <= 5-1 :
final = P * (((1 + (r/n)) ** (n*t)))
t += 1
print ("The final amount after", round(t-1), "years is", round(final,2))
When I tried to input:
1000
1
0.02
2
it will result like this:
Enter starting principle please.
Enter Compound interest rate.(daily, monthly, quarterly, half-year, yearly)
Enter annual interest amount. (decimal)
Enter the amount of years.
The final amount after 1 years is 1020.0
The final amount after 2 years is 1040.4
The final amount after 3 years is 1061.21
The final amount after 4 years is 1082.43
The final amount after 5 years is 1104.08
The problem is, it will not return to the require input number of years (e.g when I tried to input 2 years it will print up to 5 years)
Why are you setting t from input, but then immediately ignoring the input and overwriting its value with t = 1?
And where is this 5 coming from: while t-1 <= 5-1
Essentially you need a new variable for what you're doing in the loop, separate from t. And "magic numbers" like 5 appearing in code for no reason are something to be avoided.
P = int(input("Enter starting principle please.\n"))
n = int(input("Enter Compound interest rate.(daily, monthly, quarterly, half-year, yearly)\n"))
r = float(input("Enter annual interest amount. (decimal)\n"))
t = int(input("Enter the amount of years.\n"))
for t in range(1, t+1):
final = P * (((1 + (r/n)) ** (n*t)))
t += 1
print ("The final amount after", round(t-1), "years is", round(final,2))

Python discount rate of 2 items plus tax program not outputting correctly

I'm writing a program that inputs 2 items, applies a 25% discount and adds a 8.25% tax rate on the total discounted items price however I keep getting a wrong output.
It works with certain numbers such as 5 + 3 but doesn't come out correctly with 8.75 + 25.99.
first_item = int(float(input("Price of 1st item: ")))
second_item = int(float(input("Price of 2nd item: ")))
discount = (first_item + second_item) *.25
discounted_items = (first_item + second_item) - discount
tax = discounted_items *.0825
final_pay = discounted_items + tax
print("You pay ", final_pay)
expected result with 8.75 + 25.99 is 28.204537 but I keep getting 26.7918.
When you convert your input from str to float it's great, but when you convert that again to an int, you lose the fractional part (.xxx), and so you lose precision, you didn't see this problem with 3 and 5 because they're already integer, and so nothing is lost, so just keep your input float:
first_item = float(input("Price of 1st item: "))
second_item = float(input("Price of 2nd item: "))

murach python loop enhance challenge

the book says it should look like this after enhancing.
Welcome to the future value calculator
enter monthly investment: 0
Entry must be greater than 0 . Please try again.
enter monthly investment: 100
enter yearly interest rate: 16
Entry must be greater than 0 and less than or equal to 15. Please try again.
enter yearly interest rate: 12
Enter number of years: 100
Entry must be greater than 0 and less than or equal to 50
please try again.
enter number of years: 10
Year = 1 Future Value = 1280.93
Year = 2 Future VAlue = 2724.32
Year = 3 Future Value = 4350.76
Year = 4 Future Value = 6183.48
Year = 5 Future Value = 8248.64
Year = 6 Future Value = 10575.7
Year = 7 Future Value = 13197.9
Year = 8 Future Value = 16152.66
Year = 9 Future Value = 19482.15
Year = 10 Future Value = 23233.91
Continue (y/n)?
This is what I have in my program
#!/usr/bin/env python3
# display a welcome message
print("Welcome to the Future Value Calculator")
print()
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = float(input("Enter monthly investment:\t"))
yearly_interest_rate = float(input("Enter yearly interest rate:\t"))
years = int(input("Enter number of years:\t\t"))
# convert yearly values to monthly values
monthly_interest_rate = yearly_interest_rate / 12 / 100
months = years * 12
# calculate the future value
future_value = 0
for i in range(months):
future_value += monthly_investment
monthly_interest_amount = future_value * monthly_interest_rate
future_value += monthly_interest_amount
# display the result
print("Future value:\t\t\t" + str(round(future_value, 2)))
print()
# see if the user wants to continue
choice = input("Continue (y/n)? ")
print()
print("Bye!")
add data validation for the monthly investment entry. Use a while loop to check the validity of the entry and keep looping until the entry is valid. To be valid, the investment amount must be greater than zero.If it isn't, an error message like the firt one shown above should be displayed.
Use the same technique to add data validation for the interest rate and years. The interest rate must be greater than zero and less than or equal to 15. And the years must be greater than zero and less than or equal to 50. For each invalid entry, display and appropriate error message. When you're finihed, you'll have three while loops and a for loop nested within an other while loop.
Modify the statements in the for loop that calculates the future vale so one line is displayed for each year the shows the year number and future value, as shown. above. To do that, you you need to work with the integrer that's returned by the range() function.
I'm not quite sure where to put my while loops to begin enhancing.
Please check below code, let me know if it works.
#!/usr/bin/env python3
# display a welcome message
print("Welcome to the Future Value Calculator")
print()
choice = "y"
while choice.lower() == "y":
# get input from the user
while True:
monthly_investment = float(input("Enter monthly investment: "))
if monthly_investment <= 0 :
print("Entry must be greater than 0 . Please try again.")
continue
else:
break
while True:
yearly_interest_rate = float(input("Enter yearly interest rate: "))
if yearly_interest_rate <= 0 or yearly_interest_rate >= 15:
print("Entry must be greater than 0 and less than or equal to 15. Please try again.")
continue
else:
break
while True:
years = int(input("Enter number of years: "))
if years <= 0 or years >= 50:
print("Entry must be greater than 0 and less than or equal to 50")
continue
else:
break
# convert yearly values to monthly values
monthly_interest_rate = yearly_interest_rate / 12 / 100
months = years * 12
# calculate the future value
future_value = 0
for i in range(1,months+1):
future_value += monthly_investment
monthly_interest_amount = future_value * monthly_interest_rate
future_value += monthly_interest_amount
if i % 12 ==0:
# display the result
print("Year = {0} Future value:\t{1}".format(i//12,str(round(future_value, 2))))
# see if the user wants to continue
choice = input("Continue (y/n)? ")
print()
print("Bye!")

Resources