繁体   English   中英

如何使此代码更短且更自动化

[英]How do I make this code shorter and more automated

amount = eval(input("Enter the amount of money: "))

fiveHundred = amount // 500
amount = amount % 500
twoHundred = amount // 200
amount = amount % 200
oneHundred = amount // 100
amount = amount % 100
fifty = amount // 50
amount = amount % 50
twenty = amount // 20
amount = amount % 20
ten = amount // 10
amount = amount % 10
five = amount // 5
amount = amount % 5
two = amount // 2
amount = amount % 2
one = amount // 1
amount = amount % 1
print(f"You have \n"
      f"\t500 riyal: {fiveHundred} \n"
      f"\t200 riyal: {twoHundred} "
      f"\n\t100 riyal: {oneHundred} "
      f"\n\t50 riyal: {fifty} "
      f"\n\t20 riyal: {twenty} "
      f"\n\t10 riyal: {ten} "
      f"\n\t5 riyal: {five} "
      f"\n\t2 riyal: {two} "
      f"\n\t1 riyal: {one}")

它适用于任何数字输入,但我想知道是否有办法减少代码行并使其更专业。

divmod返回除法结果和余数,这就是您对每种面额所做的操作。

然后您可以为您的货币面额使用一个循环,而不必自己写出来。

最后,永远不要使用eval ,因为它允许用户输入任意代码(而且你无法确定返回的数据类型); 如果要将字符串转换为 integer,请使用int()

amount = int(input("Enter the amount of money: "))
print("You have")
for denomination in [500, 200, 100, 50, 20, 10, 5, 2, 1]:
    amount_den, amount = divmod(amount, denomination)
    print(f"\t{denomination} riyal: {amount_den}")
amount = int(input("Enter the amount of money: "))

denominations = [500,200,100,50,20,10,5,2,1]
output_denom = [0 for i in range(len(denominations))]

for index in range(len(denominations)):
    output_denom[index] = amount//denominations[index]
    amount = amount % denominations[index]

output_str = "You have \n"
for index in range(len(denominations)):
    output_str += f"\t{denominations[index]} riyal: {output_denom[index]} \n" 

print(output_str)

我的回答几乎与 AKX 的回答相同。

您可以将所有音符值收集在一个列表中,并使用 for 循环按从大到小的顺序遍历所有值,前提是它们已经按该顺序排列。 另外,当您可以只使用int() ) 时,我真的不认为需要eval() ) 。 当然,这忽略了任何无效输入的空间,如“200”或“45.9”,但我假设它对于你所要求的是不必要的。

这应该可以解决问题:

amount = int(input("Enter the amount of money: "))
notes = [500, 200, 100, 50, 20, 10, 5, 2, 1]
print("You have")
for note in notes:
    num_notes = amount // note
    print("\t{} riyal: {}".format(note, num_notes))
    amount %= note

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM