【问题标题】:How do I make this code shorter and more automated如何使此代码更短且更自动化
【发布时间】:2023-01-02 15:48:44
【问题描述】:
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 内置函数。

标签: python


【解决方案1】:

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

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

最后,永远不要使用eval,因为它允许用户输入任意代码(而且你无法确定返回的数据类型);如果要将字符串转换为整数,请使用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"	{denomination} riyal: {amount_den}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 2014-12-11
    • 2019-11-20
    • 2020-05-29
    • 2015-04-10
    相关资源
    最近更新 更多