I need to create a program that will input a money amount in the form of a floating point number. The program will then calculate which dollars and coins to make this amount. Coins will be preferred in the least number of coins. If any of the values is zero, I need to not output the value. IE: if the change is 26 cents you only need to tell the user they will receive 1 quarter and 1 penny. No more, no less.
Below is what I have so far, the only thing I cant figure out is to make the program not output the zero values
# calculate amount of change needed
dollar = 100
quarter = 25
dime = 10
nickel = 5
penny = 1
def main():
calc = True
while calc:
lst = []
mon = ['dollars', 'quaters', 'dimes', 'nickels', 'pennys']
doll = 0
quart = 0
dimes = 0
nick = 0
pen = 0
total = int(float(input('Enter amount of change: '))*100)
amount = total
while amount - dollar >= 0:
amount -= dollar
doll += 1
while amount - quarter >= 0:
amount -= quarter
quart += 1
while amount - dime >= 0:
amount -= dime
dimes += 1
while amount - nickel >= 0:
amount -= nickel
nick += 1
while amount - penny >= 0:
amount -= penny
pen += 1
lst.append(doll)
lst.append(quart)
lst.append(dimes)
lst.append(nick)
lst.append(pen)
print('\nThe change owed is: ')
print(" ")
for i, e in zip(lst, mon):
print(i, e)
calc = input("\nPress 'Y' to try again or any other key to exit: ")
if calc != 'y' and calc != 'Y':
calc = False
if __name__ == "__main__":
main()
else:
pass
I ended up solving it
if doll >= 1:
lst.append(doll)
mon.append("dollars")
if quart >= 1:
lst.append(quart)
mon.append("quarters")
if dimes >= 1:
lst.append(dimes)
mon.append("dimes")
if nick >= 1:
lst.append("nickles")
if pen >= 1:
lst.append(pen)
mon.append("pennies")
this seems to have worked
Related
My python program prints the first thing I wrote, and then loads forever and never prints the second task. What do I need to change with my code?
import random
def main():
money = 100
win = 0
loss = 0
draw = 0
bet = random.randint(5, 20)
print('You are starting with $100 and each round you will bet', bet, 'dollors')
while True:
x = random.randint(1, 6)
y = random.randint(1, 6)
z = x + y
if money == 0 or money == 200:
break
if z == 7 or z == 11:
money += bet
win += 1
elif z == 2 or z == 3 or z == 12:
loss += 1
money -= bet
else:
draw += 1
print('You ended up with', money, 'dollars, and you won', win, 'rounds, lost', \
loss, 'rounds, and drew', draw, 'rounds')
main()
Looks like it will never be able to satisfy all the conditions and is caught in a infinite loop
I think you have to use correct condition in the if condition and i suggest u to use a var to run the loop and to break the loop.
import random
def main():
money = 100
win = 0
loss = 0
draw = 0
bet = random.randint(5, 20)
print('You are starting with $100 and each round you will bet', bet, 'dollors')
loop = True
while loop:
x = random.randint(1, 6)
y = random.randint(1, 6)
z = x + y
if money <= 0 or money >= 200:
loop = False
if z == 7 or z == 11:
money += bet
win += 1
elif z == 2 or z == 3 or z == 12:
loss += 1
money -= bet
else:
draw += 1
print('You ended up with', money, 'dollars, and you won', win, 'rounds, lost', \
loss, 'rounds, and drew', draw, 'rounds')
Python 3.5
I have a project for a class to create a Roulette wheel minigame and I'm having issues. I set the initial cash to $100 and let the user play roulette. After they've given their wager and it's time to tally up the cash for the next round, I'm having issues setting the new cash value. Basically, I need to add the winnings/losings to the value of cash so that it's accurately updated for the next round. I know that declaring cash as a global variable is wrong, but we haven't learned the proper way to do it and haven't had time to check it out for myself. Anyways, the issue is near the bottom. Thank you for any help! -
import math
import random
def main():
global cash
print('Welcome to Roulette! We\'ll start you with $100')
cash = 100 #set to 100 for intitial
menu()
def menu():
print('Place your bet! ',cash,'bucks!', '''
=======================================
1. Bet on Red (pays 1:1)
2. Bet on Black (pays 1:1)
3. First 12 (pays 2:1)
4. Middle 12 (pays 2:1)
5. Last 12 (pays 2:1)
6. Choose any number (pays 35:1)
7. Cash out
Please enter your choice: ''')
menuChoice = int(input())
#Add validation!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if cash > 0 and menuChoice != 7: #Determine if quit or broke
if menuChoice == 6:
number = int(input('Please choose a number from 0-36!')) #Get their specific number
while number < 0 or number > 36: #Validation
number = int(input('Please enter a number from 0-36'))
wager = int(input('How much would you like to bet? '))
#Add validation!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
print('Press any key to spin the wheel! ')
input()
print(menuChoice, wager)
##
## ball = random.randint(0,36)
ball = 19 #set to 19 for testing. REMOVE AND RESET BALL!!!!!!!!!!!!!!!!!
if ball == 0:
color = ('green')
elif ball % 2 == 0:
color = ('black')
else:
color = ('red')
print('Your ball was',ball, 'and landed on the color',color)
#Determine if winner
if menuChoice == 1 and color == 'red':
winner = True
odds = 1
elif menuChoice == 2 and color == 'black':
winner = True
odds = 2
elif menuChoice == 3 and ball >= 1 and ball <= 12 :
winner = True
odds = 2
elif menuChoice == 4 and ball >= 13 and ball <= 24:
winner = True
odds = 2
elif menuChoice == 5 and ball >= 25 and ball <= 36:
winner = True
odds = 2
elif menuChoice == 6 and ball == number:
winner = True
odds = 35
else:
winner = False
odds = 0
#End determine if winner
if odds == 0:
pass
else:
amount = wager * odds #Get amount won/lost
print(amount)
if winner == True:
cash += amount #<~~~~~~~~~~~~~Problem Area
print('Congratulations! You won', wager,'dollars!')
print('Your total is now :',cash,'dollars.')
else:
cash -= wager
print('Sorry! You lost',wager,'dollars. Better luck next time!')
print('Your total is now :',cash,'dollars.')
input('Press a key to go back to the menu!')
print('====================================================================')
#New round
menu()
else:
print('Thank you for playing! ')
exit
main()
You could create your own python class, with the methods you already have. Than you can declare cash a class variable, with the parameter self. With self.cash you can than access the variable in every method. If that does not help please comment this answer with your issue.
I need to calculate shipping costs based on package type, weight, and how many zones the delivery goes through. I didn't get all the hard numbers from him so I'm using some placements, but that shouldn't matter much. The problem is that even though no errors are listed, running the program only returns a blank page, no prompts to enter numbers or anything like that.
Here's the code.
def main():
packageType = input('Please enter the package type: ')
rate = 0
zoneRate = 0
if packageType == 1:
rate += 1.25
elif packageType == 2:
rate += 1.5
elif packageType == 3:
rate += 1.75
elif packageType == 4:
rate += 2
weight = input('Please enter the weight: ')
if weight <= 2:
rate += 3.10
elif weight > 2 and weight <= 6:
rate += 4.20
elif weight > 6 and weight <= 10:
rate += 5.30
elif weight > 10:
rate += 6.40
zones = input('Please enter how many zones are crossed: ')
if zones == 1:
zoneRate += 5
if zones == 2:
zoneRate += 10
if zones == 3:
zoneRate += 15
cost = rate * zoneRate
print(('The shipping cost is: '), cost)
You need to have
def main():
# all of your code
# goes here
main()
I dont really know what is wrong with my code. I've been working on it for a couple of days, and have posted mulitple times on this forum, but to no avail. This is the output i receive:
The results for stock should be 8 q, 10 d, 9 n, 8 p
Also the final stock in a previous iteration needs to be the starting stock for the next iteration and so on. That is why I have the while loop. At this point if you can correct my code and post it that would be fine, I don't really care (if you really want to, even though I dont expect anyone will). Hints are great! I honestly think that the issue is syntactical or in the while loop. Any help would be beneficial!
P.s. I have to use loops, functions aren't allowed
pennies = 10
nickels = 10
dimes = 10
quarters = 10
quarters_spent = 0
dimes_spent = 0
nickels_spent = 0
pennies_spent = 0
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)
change = payment_int - in_int
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 += 1
quarters = quarters - quarters_spent
while change >= 10 and dimes > 0:
change = change - 10
dimes_spent += 1
dimes = dimes - dimes_spent
while change >= 5 and nickels > 0:
change = change - 5
nickels_spent += 1
nickels = nickels - nickels_spent
while change >= 1 and pennies > 0:
change = change - 1
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:")
if quarters_spent > 0:
print(quarters_spent, "Quarters")
if dimes_spent > 0:
print(dimes_spent, "Dimes")
if nickels_spent > 0:
print(nickels_spent, "Nickels")
if pennies_spent > 0:
print(pennies_spent, "Pennies")
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
The problem is lines like this one:
quarters = quarters - quarters_spent
Each time through the loop, you're adding 1 to quarters_spent. So the first time you subtract 1 from quarters, the next time you subtract 2 from quarters, and so on. You should just subtract 1 from quarters each time.
while change >= 25 and quarters > 0:
change -= 25
quarters_spent += 1
quarters -= 1
and similarly for the other coins.
Also, if each purchase is just supposed to show the change for that purchase, not the accumulated change from all purchases, you should set quarters_spent, dimes_spent, nickels_spent, and pennies_spent to 0 inside the loop, before calculating the change.
Can someone explain to me why this doesn't work?
I am trying to create a change machine using recursion. The first parameter is the amount of change that we need to give back, and the second parameter is an array of the number of bills with the first element representing $25, the second representing $50 and the last
representing $100.
When I call checkchange(125,[0,1,1]) it now does not return "T" or "F"
instead it just prints out
lets go
Bills: 011 Money: 125
ok the money is greater than 100
lets go
Bills: 010 Money: 25
this is the money 25
Here is the code:
def checkchange(money,bills):
tot = bills[0] * 25 + bills[1] * 50 + bills[2] * 100
print("lets go")
string = "".join(str(e) for e in bills)
print("Bills: %s Money %d" % (string,money))
if tot < money:
return "F"
elif money == 25 and bills[0] == 0:
return "F"
elif money >= 100 and bills[2] > 0:
print("ok the money is greater than 100")
money -= 100
bills[2] -= 1
checkchange(money,bills)
print("this is the money %d" % money)
elif money >= 50 and bills[1] > 0:
print("ok the money is greater than 50")
money -= 50
bills[1] -= 1
checkchange(money,bills)
elif money >= 25 and bills[0] > 0:
print("money is greater than 25")
money -= 25
bills[0] -=1
checkchange(money,bills)
else:
return "T"
The ampersand & in Python is the bitwise AND operator. It's not the same as the boolean and operator. When you have a statement like
if money == 25 & bills[0] == 0:
That's actually being read as money == (25 & bills[0]) == 0, because & binds more tightly than ==. Here's a useful chart on operator precedence
I assume the condition is wrong tot > money should be !=.
def checkchange(money,bills):
tot = bills[0] * 25 + bills[1] * 50 + bills[2] * 100
print("lets go")
if tot != money:
return "F"
if money == 25 and bills[0] == 0:
return "F"
if money >= 100 and bills[2] > 0:
print("ok the money is greater than 100")
money -= 100
bills[2] -= 1
checkchange(money,bills)
print("this is the money %d" % money)
if money >= 50 and bills[1] > 0:
print("ok the money is greater than 50")
money -= 50
bills[1] -= 1
checkchange(money,bills)
if money >= 25 and bills[0] > 0:
print("money is greater than 25")
money -= 25
bills[0] -=1
checkchange(money,bills)
return "T"
print checkchange(125,[1,0,1])
print checkchange(125,[0,1,1])
Outcome:
lets go
ok the money is greater than 100
lets go
money is greater than 25
lets go
this is the money 25
T
lets go
F