我怎么才能只打印出不为零的硬币?

2024-06-23 18:50:32 发布

您现在位置:Python中文网/ 问答频道 /正文

现在,我的代码会打印出“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/4和2个镍币,它将打印:(您有1/4、0个1角、2个镍币和0个便士)

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


Tags: to代码if硬币changearecoinmuch
2条回答

字符串连接这里是你的朋友!与其有一个非常大的打印声明,不如尝试这样的方法:

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

然后,在最后,打印出你的指纹

请注意,您可能希望在字符串中有换行符。我建议你在这里阅读字符串:http://www.tutorialspoint.com/python/python_strings.htm

让我们将硬币检查到您当前的代码中,然后构建输出字符串。请注意,我们永远不会给多个镍币。在

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

相关问题 更多 >

    热门问题