I made this program that takes change and figures out how many full dollars, and leftover change. The way it is setup, it takes the amount of change, 495 for example, and then converts it to dollars, 4.95. Now I want to cut off the .95 and leave the 4, how do I do this without it rounding up to 5? Thanks!
def main():
pennies = int(input("Enter pennies : "))
nickels = int(input("Enter nickels : "))
dimes = int(input("Enter dimes : "))
quarters = int(input("Enter quarters : "))
computeValue(pennies, nickels, dimes, quarters)
def computeValue(p,n,d,q):
print("You entered : ")
print("\tPennies : " , p)
print("\tNickels : " , n)
print("\tDimes : " , d)
print("\tQuarters : " , q)
totalCents = p + n*5 + d*10 + q*25
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)
print("Amount of Change = ", totalDollarsTrunc, "dollars and ", totalPennies ,"cents.")
if totalCents < 100:
print("Amount not = to $1")
elif totalCents == 100:
print("You have exactly $1.")
elif totalCents >100:
print("Amount not = to $1")
else:
print("Error")
In Python, int() truncates when converting from float:
>>> int(4.95)
4
That said, you can rewrite
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)
using the divmod function:
totalDollars, totalPennies = divmod(totalCents, 100)
You probably want to use math.ceil or math.floor to give you the rounding in the direction that you want.
Function int() will do just that
Related
This program will ask the user for the number of half-dollars, quarters, dimes, nickels, and pennies s/he has and then compute the total value. The total value of the change is shown both as the total number of cents and then as the separate number of dollars and cents. I want to include a final total that displays after the user is finished; which will display the total of all amounts entered throughout the session(i.e. all loop iterations). So how can I code this?
#getCoin function
def getCoin(coinType):
c = -1
while c < 0:
try:
c = int(input("How many " + coinType + " do you have? "))
if c < 0:
print("Coin counts cannot be negative. Please re-enter.")
except ValueError:
print("llegal input. Must be non-negative integer. Re-enter.")
c = -1
return c
print("Welcome to the Change Calculator")
print()
choice = input ("Do you have any change (y/n)?")
while choice.lower() == "y":
h = getCoin("Half-Dollars")
q = getCoin("Quarters")
d = getCoin("Dimes")
n = getCoin("Nickel")
p = getCoin("Pennies")
print()
TotalVal = (h*50) + (q*25) + (d*10) + (n*5) + p
print("You have " + str(TotalVal) + " cents.")
dollars = TotalVal // 100 # // is for division but only returns whole num
cents = TotalVal % 100 # % is for modulos and returns remainder of whole number
print("Which is " + str(dollars) + " dollars and " + str(cents) + " cents.")
choice = input("Do you have more change (y/n)? ")
print("Thanks for using the change calculator.")
finalTotal = TotalVal
print("You had a total of" + finalTotal + " cents.")
print("Which is" + str(finalTotalDollars) + " dollars and" + str(finalTotalCents) + " cents.")
To make it so when a user wants to play again, you could use an external file to write to and read from using open, read and write, to store user info.
You could use notepad as .txt and write user name, money, and repeat, so login checks and calls the money at the line after the name.
I am new to coding and Python in general, and I can't figure this out.
I added loops so that the program does not terminate every time there is a typo, however I messed up something with the second loop presumably.
I think it might be connected to the whitespace, but I can't figure it out.
The Programm terminates after taking in the "calories_burned" variable.
def start():
print("""This is a Weight Calculator, please follow the instructions.""")
name = input("What is your name? ")
age = int(input("How old are you? "))
if 19 <= age <= 78:
height = float(input("How tall are you in cm? "))
current_weight = float(input("How much do you currently weigh? "))
goal_weight = float(input("How much do you want to weigh? "))
calories_consumed = int(input("How many calories did you consume today? "))
calories_burned = int(input("How many calories did you burn today? "))
def activity():
global rmr
activity_factor = input("Choose an activity factor: Sedentary, Lightly active, Moderately Active, Very Active ")
zif activity_factor == "sedentary":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.2))
if activity_factor == "lightly active":
rmr = int(round((10 * current_weight + 6.25 * height - 5 * age + 5) * 1.375))
if activity_factor == "moderately active":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.550))
if activity_factor == "very active":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.725))
else:
activity()
daily_deficit = int((rmr + calories_burned - calories_consumed))
print("Your daily deficit is: " + str(daily_deficit))
import numpy
mean_deficit = [daily_deficit]
calculation_mean_deficit = int(round(7500 / numpy.mean(mean_deficit)))
reach_goal = int(round((current_weight - goal_weight) * calculation_mean_deficit))
print(mean_deficit)
print(name + " it will take you " + str(calculation_mean_deficit) + " days to loose 1 kg.")
print(name + " it will take you " + str(reach_goal) + " days to reach your goal.")
choice = input("do you wish to continue Y/N?")
if choice == "n":
return
else:
start()
else:
print("Invalid age")
start()
start()
You don't call the activity() function anywhere in your code, so once the program collects the inputs it doesn't do anything else and exits.
Also it's "lose" not "loose"
Why am i getting this error? The picture has the details. I need to get the _spent values to print the proper amount of times. So, say it runs through the loop 3 times, I need it to print 3. I think that is where the 1s are coming from. I don't like it!
pennies = 10
nickels = 10
dimes = 10
quarters = 10
print("\nWelcome to change-making program.")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
while in_str.lower() != 'q':
dollar_str, cents_str = in_str.split(".")
if in_str.lower() == 'q':
quit()
in_int = int(float(in_str) * 100)
if in_int < 0:
print("Error: purchase price must be non-negative.")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
if in_int > 0:
payment = input("\nInput dollars paid: ")
payment_int = int(float(payment) * 100)
change = payment_int - in_int
#determines if there payment input
if payment_int < in_int:
print("Error: Insufficient payment.")
payment = input("\nInput dollars paid: ")
payment_int = int(float(payment) * 100)
if change == 0:
print("No change.")
#determines how many quarters, dimes, nickels, and pennies are left
while change >= 25 and quarters > 0:
change = change - 25
quarters_spent = 0
quarters_spent += 1
quarters = quarters - quarters_spent
print(quarters_spent)
while change >= 10 and dimes > 0:
change = change - 10
dimes_spent = 0
dimes_spent += 1
dimes = dimes - dimes_spent
print(dimes_spent)
while change >= 5 and nickels > 0:
change = change - 5
nickels_spent = 0
nickels_spent += 1
nickels = nickels - nickels_spent
print(nickels_spent)
while change >= 1 and pennies > 0:
change = change - 1
pennies_spent = 0
pennies_spent += 1
pennies = pennies - pennies_spent
if quarters == 0 and dimes == 0 and nickels == 0 and pennies == 0:
print("Error: ran out of coins.")
quit()
print("\nCollect Payment Below:")
print(10 - quarters, "Quarters")
print("\nStock: ", quarters, "Quarters, ", dimes, " Dimes, ", nickels, " Nickels, ", pennies, " Pennies ")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
pennies = pennies
nickels = nickels
dimes = dimes
quarters = quarters
This error implies that you didn't define the value nickels_spent before trying to use it.
I guess the error is in this line: print (nickels_spent).
What is probably happening is that the while statement condition that is used to assign a value to that variable is not true when you try to run it, so it wasn't defined but you still try to use it.
Try debugging before that while loop to see what exactly happens there.
You only defined and initialized this variable nickels_spent inside the while loop
However, if the condition is not met, the program will skip the loop and jump to execute this print(nickels_spent) statement where this variable is not yet defined.
You can either
Move the print statement into the while loop
Or
Define and initialize this variable outside the while loop.
Depends on the purpose of your program
I cannot seem to figure out why when i run my program i receive the error ValueError: invalid literal for int() with base 10: 'Enter pennies : '.
The entire program was made by my instructor so we could add the functions to make it work. im currently trying to define get_input1 but im having no luck. any help would be great.
def main():
pennies = get_input1("Enter pennies : ")
nickels = get_input("Enter nickels : ")
dimes = get_input("Enter dimes : ")
quarters = get_input("Enter quarters : ")
print("You entered : ")
print("\tPennies : " , pennies)
print("\tNickels : " , nickels)
print("\tDimes : " , dimes)
print("\tQuarters : " , quarters)
total_value = get_total(pennies, nickels, dimes, quarters)
dollars = get_dollars(pennies, nickels, dimes, quarters)
left_over_cents = get_left_over_cents(pennies, nickels, dimes, quarters)
print("Total = $", total_value, sep="")
print("You have", dollars, "dollars and", left_over_cents, "cent(s)")
def get_input1(pennies):
int(input("Enter Pennies: "))
if int(pennies) < 0:
print('Error: money cannot be negative')
pennies = int(input('Enter correct amount of pennies: '))
main()
change this:
int(input("Enter Pennies: "))
to this:
pennies = input("Enter Pennies: ")
Edited
I believe this is just a typo, you should be assigning pennies to the input result.
def main():
pennies = get_input1("Enter pennies : ")
nickels = get_input2("Enter nickels : ")
dimes = get_input3("Enter dimes : ")
quarters = get_input4("Enter quarters : ")
print("You entered : ")
print("\tPennies : " , pennies)
print("\tNickels : " , nickels)
print("\tDimes : " , dimes)
print("\tQuarters : " , quarters)
total_value = get_total(pennies, nickels, dimes, quarters)
dollars = get_dollars(pennies, nickels, dimes, quarters)
left_over_cents = get_left_over_cents(pennies, nickels, dimes, quarters)
print("Total = $", total_value, sep="")
print("You have", dollars, "dollars and", left_over_cents, "cent(s)")
def get_input1(pennies):
pennies = int(input("Enter Pennies: "))
if int(pennies) < 0:
print('Error: money cannot be negative')
pennies = int(input('Enter correct amount of pennies: '))
return(pennies)
def get_input2(nickels):
nickels = int(input("Enter nickels: "))
if int(nickels) < 0:
print('Error: money cannot be negative')
pennies = int(input('Enter correct amount of nickels: '))
return(nickels)
def get_input3(dimes):
dimes = int(input("Enter dimes: "))
if int(dimes) < 0:
print('Error: money cannot be negative')
pennies = int(input('Enter correct amount of dimes: '))
return(dimes)
def get_input4(quarters):
quarters = int(input("Enter quarters: "))
if int(quarters) < 0:
print('Error: money cannot be negative')
pennies = int(input('Enter correct amount of quarters: '))
return(quarters)
main()
This will get you through defining your pennies,nickels,dimes and quarters. Now you will have to define get_total, get_dollar, and get_left_over_cents.
You needed to have pennies in front of the int value is why you were receiving the error. Then you can return that value of pennies to the main.
Hope this helps!
Your data flow is backwards. In main(), you're calling get_input1 to retrieve values, much as with input(), but if we look at that get_input1 does:
# Names its argument, which was a question, "pennies"
def get_input1(pennies):
# Asks a question, converts to int, and discards it
int(input("Enter Pennies: "))
if int(pennies) < 0: # Converts pennies to int; but it was a question!
print('Error: money cannot be negative')
# This is the only place to alter pennies, but it doesn't return it
pennies = int(input('Enter correct amount of pennies: '))
It looks like this used to be code that was refactored to handle the various coins with a function call each, but it doesn't have the two modifications it needs: a way to alter what it asks for, and a way to return what the answer was. Note that function arguments, like pennies in get_input1, are local variables; main never sees it changing.
I need to code a get_input function that has loop validation so the number cannot be less than 0
This is the program. ive made this a global function but my instructor told me it was wrong. Making get_input a global function seems to work but i need to use the means of
def get_input():
get_input()
Ive been setting up the global function as get_input = input just because i have no clue how to do what i posted above without geting the error "global name is not defined".
Any help would be greatly appreciated
get_input = input
def main():
pennies = get_input("Enter pennies : ")
nickels = get_input("Enter nickels : ")
dimes = get_input("Enter dimes : ")
quarters = get_input("Enter quarters : ")
print("You entered : ")
print("\tPennies : " , pennies)
print("\tNickels : " , nickels)
print("\tDimes : " , dimes)
print("\tQuarters : " , quarters)
total_value = get_total(pennies, nickels, dimes, quarters)
dollars = get_dollars(pennies, nickels, dimes, quarters)
left_over_cents = get_left_over_cents(pennies, nickels, dimes, quarters)
print("Total = $", total_value, sep="")
print("You have", dollars, "dollars and", left_over_cents, "cent(s)")
main()
Looks like you need to just put all your raw_input statements inside your get_input function.
def get_input(currency):
currency = -1.0
while currency < 0:
try:
currency = float(raw_input("Enter %s: ", % (currency)))
except ValueError:
print "Invalid input!"
currency = -1.0
continue
if currency < 0:
print "Can't have negative money!"
else:
return currency
def main():
pennies = get_input("pennies")
nickles= get_input("nickles")
dimes= get_input("dimes")
quarters= get_input("quarters")
Then so on with your program