簡體   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