我如何使这段代码更短,更自动化


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"nt100 riyal: {oneHundred} "
f"nt50 riyal: {fifty} "
f"nt20 riyal: {twenty} "
f"nt10 riyal: {ten} "
f"nt5 riyal: {five} "
f"nt2 riyal: {two} "
f"nt1 riyal: {one}")

它工作得很好与任何数字输入,但我想知道是否有一种方法来减少代码行,使它更专业。

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"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()。当然,这忽略了像"两百"这样的无效输入的任何空间。或"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

最新更新