Josh Dombal
Josh Dombal

Reputation: 155

How do I only print out the value of coins that are not zero?

Right now, my code prints out "0 dimes" or "0 pennies" if there are no dimes or pennies, I need to know how to make it so that if there are 0 of a specific coin, that nothing will print for that coin.

  #Asks user how much change they are trying to give, returns the coins to make that change

  coin = int(input("How much change are you tring to give (in cents)? "))


  while coin >= 25: 

      quarters = coin // 25
      coin = coin % 25

      if coin >= 10:
          dimes = coin // 10
          coin = coin % 10

      if coin >= 5:
          nickels = coin // 5
          coin = coin % 5

      pennies = coin // 1
      coin %= 1

      print ("You have ",quarters,"quarters", dimes, "dimes,",nickels,"nickels and ",pennies,"pennies.")

For example, if the change is 1 quarter and 2 nickels, it will print: (You have 1 quarter, 0 dimes, 2 nickels and 0 pennies)

I need it to print (You have 1 quarter and 2 nickels)

Upvotes: 0

Views: 582

Answers (2)

Prune
Prune

Reputation: 77857

Let's work the coin checks into your current code, and build up the output string as we go. Note that we'll never give multiple nickels.

# Asks user how much change they are trying to give, returns the coins to make that change

coin = int(input("How much change are you trying to give (in cents)? "))
change = ""

while coin >= 25:

    quarters = coin // 25
    coin = coin % 25
    if quarters > 0:
        change += str(quarters) + " quarters "

    if coin >= 10:
        dimes = coin // 10
        coin = coin % 10
        change += str(dimes) + " dimes "

    if coin >= 5:
        nickels = coin // 5
        coin = coin % 5
        change += str(nickels) + " nickel "

    pennies = coin // 1
    coin %= 1
    if pennies > 0:
        change += str(pennies) + " pennies "

    print (change)

Upvotes: 0

Lando
Lando

Reputation: 417

String concatenation here is your friend! Instead of having one really big print statement, try something like this:

print_str = ''
if quarters > 0:
    print_str += 'You have ' + str(quarters) + ' quarters.'

And then, at the end, print your print_str.

As a note, you may want to have line breaks in your string. -- I'd recommend reading up on strings here: http://www.tutorialspoint.com/python/python_strings.htm

Upvotes: 1

Related Questions