我目前正在学习使用python进行编程。我正在尝试建立一个基本程序,根据用户输入的数量输出每种类型的硬币(四分之一,镍,一角钱,便士)中的多少。我目前拥有它,因此它将打印0.但是,我希望在print
语句中省略这些值。我不确定如何在不制作每个不同的总值并让它们从if语句中打印出来的情况下如何做到这一点。
#for if statement and to ask for what coin number it is
y = 1
#asks user for how many coins
x = int(input("How much change are you trying to give (in cents)? "))
while(y <= 1):
q = 25
d = 10
n = 5
p = 1
#Take total and divide by 25 as many times as you can output as quarter
totalq = x // 25
#Take total from that and divide by 10 as many times as you can and output as dime
totald = (x-(q*(totalq))) // 10
#Take total from above and divide by 5 as many times as you can and output as nickel
totaln = (x-(q*(totalq))-(d*(totald))) //5
#Finally take total from above and see how many is left over and output as penny
totalp = (x-(q*(totalq))-(d*(totald))-(n*(totaln))) // 1
y = y + 1
total = (str(totalq) +" quarters " + str(totald) +" dimes " + str(totaln) +" nickels " + str(totalp) + " pennies")
print(total)
答案 0 :(得分:0)
我认为,最简单的方法是,正如您所建议的那样,使用一堆if
s - 类似于:
if totalq:
print(totalq, "quarters", end=' ')
if totald:
print(totalq, "dimes", end=' ')
if totaln:
print(totalq, "nickels", end=' ')
if totalp:
print(totalq, "pennies")
或者,你可以使用生成器表达式重复一点:
pairs = [(totalq, 'quarters'),
(totald, 'dimes'),
(totaln, 'nickels'),
(totalp, 'pennies')]
total = ' '.join(str(value) + ' ' + name
for value, name in pairs
if value)
print(total)
就个人而言,我认为后一种方法更漂亮,但它也有点复杂。如果您对后一个代码有所了解,请不要理解,请告诉我。