我如何只打印出不为零的硬币值?

时间:2015-10-14 22:37:36

标签: python python-3.x if-statement while-loop printf

现在,我的代码打印出“0角钱”或“0便士”,如果没有硬币或硬币,我需要知道如何制作它,以便如果有一个特定的硬币0,那么什么都不打印那枚硬币。

  #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.")

例如,如果更改为1个季度和2个镍币,则会打印:(您有1个季度,0个角钱,2个镍币和0个便士)

我需要它来打印(你有1个季度和2个镍币)

2 个答案:

答案 0 :(得分:1)

这里的字符串连接是你的朋友!不要有一个非常大的印刷声明,尝试这样的事情:

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

然后,最后打印你的print_str。

作为备注,您可能希望在字符串中包含换行符。 - 我建议在这里阅读字符串:http://www.tutorialspoint.com/python/python_strings.htm

答案 1 :(得分:0)

让硬币检查你当前的代码,并在我们去的时候建立输出字符串。请注意,我们永远不会给出多个镍币。

static