【问题标题】:How can I only print a value if it is greater than zero?如果它大于零,我怎样才能只打印一个值?
【发布时间】:2022-11-04 01:23:21
【问题描述】:

我正在创建一个硬币回报计算器。我已经编写了所有代码,但我不知道如何只显示需要的硬币而不是获取我不需要的硬币。

Enter change amount to convert: 3
0 quarter(s)
0 dime(s)
0 nickle(s)
3 penny(ies)
Want to calculate another amount? (y/n): 

我不想显示硬币、硬币或镍币。

while True:
    change = input("Enter change amount to convert: ")
    if str(change).isnumeric():
        change = int(change)
        if change < 100:
            quarters, dimes, nickels, pennies = coinCalc(change)
            print(quarters, "quarter(s)")
            print(dimes, "dime(s)")
            print(nickels, "nickle(s)")
            print(pennies, "penny(ies)")
            print("Want to calculate another amount? (y/n): ")
            answer = input()
            if answer == "n":
                print("Bye!")
                break
        else:
            print("Error! Invalid integer entered please try again.")
    else:
        print("Error! Invalid integer entered please try again.")

【问题讨论】:

  • 一种选择是在打印之前检查数字是否大于 0,例如 if quarters &gt;0: print(quarters); if dimes &gt;0...
  • 这与pytest有什么关系?
  • 如果金额小于 100,您为什么不使用已经用于计算零钱的相同技术?

标签: python


【解决方案1】:

您可以添加一个 if 语句来检查硬币的价值是否为零。如果是这样,那么不要打印它。

if quarters != 0:
    print(quarters, "quarter(s)")
if dimes != 0:
    print(dimes, "dime(s)")
if nickels != 0:
    print(nickels, "nickle(s)")
if pennies != 0:
    print(pennies, "penny(ies)")
print("Want to calculate another amount? (y/n): ")

【讨论】:

  • 你不应该用括号括起来条件,它没有用。
猜你喜欢
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-04
  • 2019-06-01
相关资源
最近更新 更多