这个 python 代码有改进吗?
Is there an improvement for this python code?
我写了很简单的 Python 代码来添加各种美元钞票或硬币,结果很长。如果有什么改进请指教,让我提高效率。
#User input
a = int(input('Enter the number of hundreds: '))
b = int(input('Enter the number of fifties: '))
c = int(input('Enter the number of twenties: '))
d = int(input('Enter the number of tens: '))
e = int(input('Enter the number of fives: '))
f = int(input('Enter the number of one: '))
g = int(input('Enter the number of quarters: '))
h = int(input('Enter the number of dimes: '))
i = int(input('Enter the number of nickels: '))
j = int(input('Enter the number of pennies: '))
def hun(k):
return 100 * k
def fif(l):
return 50 * l
def twe(m):
return 20 * m
def ten(n):
return 10 * n
def fiv(o):
return 5 * o
def one(p):
return 1 * p
def qua(q):
return .25 * q
def dim(r):
return .10 * r
def nic(s):
return .05 * s
def pen(t):
return .01 * t
# Final computation
total = hun(a) + fif(b) + twe(c) + ten(d) + fiv(e) + one(f) + qua(g) + dim(h) + nic(i) + pen(j)
print('The total amount is $', total)
您可以使用字典和 sum()
方法改进您的代码:
c = {'hundreds':100,
'fifties':50,
'twenties':20,
'tens':10,
'fives':5,
'one':1,
'quarters':.25,
'dimes':.1,
'nickels':.05,
'pennies':.01}
total = sum(int(input(f"Enter the number of {k}: "))*c[k] for k in c)
print(f"The total amount is ${total}.")
我写了很简单的 Python 代码来添加各种美元钞票或硬币,结果很长。如果有什么改进请指教,让我提高效率。
#User input
a = int(input('Enter the number of hundreds: '))
b = int(input('Enter the number of fifties: '))
c = int(input('Enter the number of twenties: '))
d = int(input('Enter the number of tens: '))
e = int(input('Enter the number of fives: '))
f = int(input('Enter the number of one: '))
g = int(input('Enter the number of quarters: '))
h = int(input('Enter the number of dimes: '))
i = int(input('Enter the number of nickels: '))
j = int(input('Enter the number of pennies: '))
def hun(k):
return 100 * k
def fif(l):
return 50 * l
def twe(m):
return 20 * m
def ten(n):
return 10 * n
def fiv(o):
return 5 * o
def one(p):
return 1 * p
def qua(q):
return .25 * q
def dim(r):
return .10 * r
def nic(s):
return .05 * s
def pen(t):
return .01 * t
# Final computation
total = hun(a) + fif(b) + twe(c) + ten(d) + fiv(e) + one(f) + qua(g) + dim(h) + nic(i) + pen(j)
print('The total amount is $', total)
您可以使用字典和 sum()
方法改进您的代码:
c = {'hundreds':100,
'fifties':50,
'twenties':20,
'tens':10,
'fives':5,
'one':1,
'quarters':.25,
'dimes':.1,
'nickels':.05,
'pennies':.01}
total = sum(int(input(f"Enter the number of {k}: "))*c[k] for k in c)
print(f"The total amount is ${total}.")