[英]How do I only print out the value of coins that are not zero?
Right now, my code prints out "0 dimes" or "0 pennies" if there are no dimes or pennies, I need to know how to make it so that if there are 0 of a specific coin, that nothing will print for that coin. 现在,如果没有零钱或一分钱,我的代码会打印出“ 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.")
For example, if the change is 1 quarter and 2 nickels, it will print: (You have 1 quarter, 0 dimes, 2 nickels and 0 pennies) 例如,如果更改为1个季度和2个镍币,它将打印:(您有1个季度,0个角钱,2个镍币和0个便士)
I need it to print (You have 1 quarter and 2 nickels) 我需要打印(您有1个季度和2个镍币)
String concatenation here is your friend! 字符串串联在这里是您的朋友! Instead of having one really big print statement, try something like this:
而不是使用一个非常大的打印语句,请尝试如下操作:
print_str = ''
if quarters > 0:
print_str += 'You have ' + str(quarters) + ' quarters.'
And then, at the end, print your print_str. 然后,最后打印您的print_str。
As a note, you may want to have line breaks in your string. 注意,您可能想在字符串中使用换行符。 -- I'd recommend reading up on strings here: http://www.tutorialspoint.com/python/python_strings.htm
-建议您在此处阅读字符串: http : //www.tutorialspoint.com/python/python_strings.htm
Let's work the coin checks into your current code, and build up the output string as we go. 让我们将硬币检查工作到当前代码中,然后逐步构建输出字符串。 Note that we'll never give multiple nickels.
请注意,我们绝不会给多个镍。
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.