Python如果条件打印或不打印

时间:2017-09-17 21:42:46

标签: python python-3.x if-statement

这是一个基本的数学问题。我想计算最少的纸币数量。

这是我的代码,运作良好。

total_payment = int(input("Please enter the total amount: "))

Dollar50 = int(total_payment // 50)
remaining_money = total_payment % 50

Dollar20 = int(remaining_money // 20)
remaining_money = remaining_money % 20

Dollar10 = int(remaining_money // 10)
remaining_money = remaining_money % 10

Dollar5 = int(remaining_money // 5)
remaining_money = remaining_money % 5

Dollar1 = int(remaining_money // 1)

print("We need {0} 50 dollar.".format(Dollar50))
print("We need {0} 20 dollar.".format(Dollar20))
print("We need {0} 10 dollar.".format(Dollar10))
print("We need {0} 5 dollar.".format(Dollar5))
print("We need {0} 1 dollar.".format(Dollar1))

但我只想在使用这种类型的钞票时打印。例如,如果总金额是101美元而不是程序打印

We need 2 50 dollar.  
We need 0 20 dollar.
We need 0 10 dollar.
We need 0 5 dollar.
We need 1 1 dollar.

但我不想打印0值的那些。我只想要它打印

We need 2 50 dollar.
We need 1 1 dollar.

这是我斗争的一个例子。我不能编码这种循环或条件。非常感谢您的帮助。

5 个答案:

答案 0 :(得分:1)

而不是为所有这些语句写if语句只是zip它们并使用for循环:

counts = [Dollar50, Dollar20, Dollar10, Dollar5, Dollar1]
ammounts = [50, 20, 10, 5, 1]
for i, j in zip(counts, ammounts):
    if i:
        print("We need {} {} dollar.".format(i, j))

答案 1 :(得分:0)

使用

if Dollar50:
  print("We need {0} 50 dollar.".format(Dollar50))

如果值为0,则不会打印任何内容。

答案 2 :(得分:0)

这样做的一种方法是创建一个数组来存储所有账单的值来循环,但是这需要一些重写,以使它与你目前所需的if-tree树一起工作< / p>

例如

if Dollar50 > 0:
     print("We need {0} 50 dollar.".format(Dollar50))

您可以针对所有不同的帐单尺寸继续使用此逻辑

答案 3 :(得分:0)

简单地说,只需在每个print语句周围添加一个if语句,检查0。

if Dollar50 != 0:
    print("We need {0} 50 dollar.".format(Dollar50))
if Dollar20 != 0:
    print("We need {0} 20 dollar.".format(Dollar20))

为每个项目继续。

答案 4 :(得分:0)

你需要的只是一个if条件。

作为练习,你应该尝试写DRY code。使用循环和列表看起来像这样

face_values = [50, 20, 10, 5, 1]
amounts = [0]*5
remaining_money = int(input("Please enter the total amount: "))

# While you have money left, calculate the next most 'dollar_value' you can use
i = 0  # This is an index over the 'dollars' list
while remaining_money > 0:
  d = face_values[i]
  amounts[i] = remaining_money // d
  remaining_money %= d
  i+=1

denomination = "dollar bill"
denomination_plural = denomination + "s"

# Iterate both values and amounts together and print them
for val, amount in zip(face_values, amounts):
  if amount == 1:  # Filter out any non-positive amounts so you don't show them
    print("We need {} {} {}.".format(val, amount, denomination))
  else if amount > 1:
    print("We need {} {} {}.".format(val, amount, denomination_plural))