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
Related
I'm trying to write a simple program to test out the basics of Python I've been learning. I decided to do a simple tongue in cheek gambling script that checks a user entered number against a 1,100 random generated number. I want to multiply the users stake by a different amount depending on how close to the random number the user guessed, but cant seem to get it to check within a range using == or <= etc. Or at least cant work it out.
i.e, user stakes 10 on number 15.
if the random number is 20 it's within 5 of the users number so multiply the stake by 25.
if the random number is 25 its within 10 or less of the users number so multiply by 10 etc.
Here's what I've got, would love to hear any advice on this!
if random_number == int(playernumber):
playerstake = int(playerstake) * 100
print("\nCongratulations, you hit the JACKPOT and won £" + str(playerstake) + "!!!")
#+/- 1
elif int(playernumber) == int(random_number) + 1:
playerstake = int(playerstake) * 50
print("\nCongratulations, you guessed within 1 of " + str(random_number) + " and won £" + str(playerstake) + "!")
elif int(playernumber) == int(random_number) - 1:
playerstake = int(playerstake) * 50
print("\nCongratulations, you guessed within 1 of " + str(random_number) + " and won £" + str(playerstake) + "!")
#+/- 5
elif int(playernumber) == int(random_number) + 5:
playerstake = int(playerstake) * 20
print("\nCongratulations, you guessed within 5 of " + str(random_number) + " and won £" + str(playerstake) + "!")
elif int(playernumber) == int(random_number) - 5:
playerstake = int(playerstake) * 20
print("\nCongratulations, you guessed within 5 of " + str(random_number) + " and won £" + str(playerstake) + "!")
etcetc
I understand this currently doesn't work because I'm == random number + 1
so 12 would be 13.
Apologies if I've done something frowned upon here, this was my first script I tried to tackle and wanted to see the potential ways to have done this 'properly'. Thanks for the replies!
If I'm understanding correctly, much simpler code:
dist = abs(guess - rand_num)
if dist == 0:
multiplier = 100
elif dist <= 1:
multiplier = 50
elif dist <= 5:
multiplier = 20
elif dist <= 10:
multiplier = 10
else:
multiplier = 0
player_stake += player_stake * multiplier
if dist == 0:
print("Congratulations you've won")
else:
print("Congratulations you guessed {0} within {1} and won ${3}".format([multiplier, rand_num, player_stake])
Here's a simple solution. I'll let you discover how it works!
pn = int(player_number)
rn = random_number
if rn == pn:
print("You won!")
elif rn in range(pn-1, pn+1+1): # range goes up to the final value (less than), so you need a +1
print("You won +- 1!")
elif rn in range(pn-5, pn+5+1):
print("You won +- 5!")
else:
print("You lost!")
The next chlallenge would be to make the 'checks', +-1, +-5, an array of values, but that was outside the scope of your question.
Don't repeat yourself. You could replace your if clauses with a lookup table. With only 3 things, its a toss-up whether this is better, but generally, if the logic is the same within multiple conditional clauses, its good to pull that logic out into a single implementation. The lookup table lets you change the boundaries used for selection without touching the logic.
# assumes `diff`, `random_number` and `playerstake` defined at time of use
exact_text = f"Congratulations, you hit the JACKPOT and won £{playerstake}"
near_text = f"Congratulations, you guessed within {diff} of {random_number} and won £{playerstake}"
# lookup table: (diff, payout, text)
odds = [
(0, 100, exact_text),
(1, 50, near_text),
(5, 20, near_text)
]
playernumber = int(playernumber)
playerstake = int(playerstake)
player_diff = abs(random_number - playernumber)
for diff, payout, text in odds:
if player_diff <= diff:
playerstake *= payout
print(text)
break
else:
print(f"You were {player_diff} away from the random number")
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
I am a first year programming student and I am having trouble trying to get my code to loop properly and I would like some pointers on how I can get it to run as desired. I am running a program that will calculate change with a preset stock of 10 of each coin, price and payment will be input by the user and change will be returned by the number of coins left in the stock. Right now i am having difficulties trying to get the program to return the 'insufficient funds' and the 'no change' print statements and trying to get it to loop over from quarters to dimes to nickels and pennies properly, I am not sure what I could be doing wrong.
quarters = 10
dimes = 10
nickels = 10
pennies = 10
stock = quarters, dimes, nickels, pennies
print("\nWelcome to change-making program.")
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(
quarters, dimes, nickels, pennies))
in_str = float(input("Enter the purchase price (xx.xx) or 'q' to quit: "))
payment_int = int(input("Input dollars paid (int):"))
change_sum = float(payment_int) - in_str
#in_str = float(input("Enter the purchase price (xx.xx) or 'q' to quit: "))
while change_sum >= 0:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
else:
if quarters > 0 and change_sum >= 0.25:
change_sum = change_sum - 0.25
quarters -= 1
print(quarters, change_sum)
elif dimes > 0 and 0.25 > change_sum >= 0.10:
change_sum = change_sum - 0.1
dimes -= 1
print(dimes, change_sum)
elif nickels > 0 and 0.1 > change_sum >= 0.05:
change_sum = change_sum - 0.05
nickels -= 1
print(nickels, change_sum)
elif pennies > 0 and 0.05 > change_sum >= 0.01:
change_sum = change_sum -0.01
pennies -=1
print(pennies, change_sum)
else:
if change_sum == 0.0:
break
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(
quarters, dimes, nickels, pennies))
print(change_sum)
If the fund is insufficient, then change_sum is <0 and the while loop never runs. That's why you don't get "insufficient fund" message. You should first check the sufficiency and then start the loop:
Just change this part:
while change_sum >= 0:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
else:
if quarters > 0 and change_sum >= 0.25:
to this:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
while change_sum >= 0:
if quarters > 0 and change_sum >= 0.25:
I am trying to make a full-on guessing game with a shop that you can buy stuff with coins. but I had a function that was supposed to give the user a certain amount of coins depending on how many attempts it took them to guess the number. However, when I have a variable called 'coins' and when a player gets the number, I add coins to 'coins' it doesn't actually add coins. When I print 'coins' it still tells me 0. It's very confusing I know but I just want to fix this. I am using a mac with python 3, and am using two files, one for the main code, and the other for the functions. Do you see where I'm going wrong?
Main Code:
from guessing_functions import guess_game, guess_home
home = False
attempt = 0
coins = 0
print ("Atemps:Coins, 10:5, 7:10, 5:20, 3:40, 1:100 ")
guess_game(coins, attempt)
while not home:
guess_home(coins)
Functions:
import random
def guess_game(coins, attempt):
print ("This is a guessing game. ")
found = False
num = random.randint(1, 100)
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == num:
print ("You got it!")
found = True
elif userGuess > num:
print ("Guess Lower!")
else:
print ("Guess Higher")
attempt += 1
if attempt == 1 and found == True:
print ("You won 100 coins!")
coins += 100
elif attempt == 2 and found == True:
print ("You won 40 coins")
coins += 40
elif attempt == 3 and found == True:
print ("You won 40 coins")
elif attempt == 4 and found == True:
print ("You won 20 coins")
coins += 20
elif attempt == 5 and found == True:
print ("You won 20 coins")
coins += 20
elif attempt == 6 and found == True:
print ("You won 10 coins")
coins += 10
elif attempt == 7 and found == True:
print ("You won 10 coins")
coins += 10
elif attempt == 8 and found == True:
print ("You won 5 coins")
coins += 5
elif attempt == 9 and found == True:
print ("You won 5 coins")
coins += 5
elif attempt == 10 and found == True:
print ("You won 5 coins")
coins += 5
Your function uses coins in it's local scope. In order for the function to change the value of the outter scope (global) coins variable you need to explicity state that.
Add global coins inside your function before changing coins value.
coins = 0
def f():
global coins
coins = 5
f()
print coins
# 5
Or, an alternative way is to return coins value from the function, and call your function coins = guess_game(attempt)
Here is some useful resource for this subject
To get it to work, you need only add return coins to the end of the guess_game function and collect the returned value in your main code as coins = guess_game(coins, attempt). However, if you'd like, you can simplify your code a little bit like so:
import random
def guessing_game(coins):
print("This is a guessing game. ")
attempts = 0
number = random.randint(1, 100)
user_guess = -number
while user_guess != number:
user_guess = int(input("Your Guess: "))
if user_guess > number:
print("Guess Lower!")
elif user_guess < number:
print("Guess Higher")
else:
print("You got it!")
if attempts == 1:
winnings = 100
elif attempts in [2, 3]:
winnings = 40
elif attempts in [4, 5]:
winnings = 20
elif attempts in [6, 7]:
winnings = 10
elif attempts in [8, 9, 10]:
winnings = 5
else:
winnings = 0
print("You won {} coins!".format(winnings))
return coins + winnings
attempts += 1
With your main code as:
from guessing_functions import guessing_game
coins = 0
print("Starting balance: {} coins".format(coins))
print ("Winnings vs. Attempts: 10:5, 7:10, 5:20, 3:40, 1:100")
coins = guessing_game(coins)
print("Current balance: {} coins".format(coins))
Where the output from a sample run is as follows:
Starting balance: 0 coins
Winnings vs. Attempts: 10:5, 7:10, 5:20, 3:40, 1:100
This is a guessing game.
Your Guess: 50
Guess Lower!
Your Guess: 25
Guess Higher
Your Guess: 37
Guess Higher
Your Guess: 44
Guess Higher
Your Guess: 47
Guess Lower!
Your Guess: 46
You got it!
You won 20 coins!
Current balance: 20 coins
You should return the number of coins from the function and assign it to coins:
def guess_game(coins, attempt):
... # code to determine coin amount
return coins
coins = guess_game(coins, attempt)
Defining Functions
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.