gpt4 book ai didi

Python:我可以做些什么来精简我的 Python 代码?

转载 作者:太空宇宙 更新时间:2023-11-04 10:49:53 25 4
gpt4 key购买 nike

我可以用不同的代码来简化这个 Python 源代码的重点吗?该程序的重​​点是获取用户总金额并将其添加到运费中。运费由国家(加拿大或美国)和产品价格决定:125.00 美元的产品在加拿大的运费是 12.00 美元。


input ('Please press "Enter" to begin')

虽然是真的: print('这将计算运费和您的总计。')

totalAmount = int(float(input('Enter your total amount: ').replace(',', '').replace('$', '')))
Country = str(input('Type "Canada" for Canada and "USA" for USA: '))

usa = "USA"
canada = "Canada"
lessFifty = totalAmount <= 50
fiftyHundred = totalAmount >= 50.01 and totalAmount <= 100
hundredFifty = totalAmount >= 100.01 and totalAmount <= 150
twoHundred = totalAmount

if Country == "USA":
if lessFifty:
print('Your shipping is: $6.00')
print('Your grand total is: $',totalAmount + 6)
elif fiftyHundred:
print('Your shipping is: $8.00')
print('Your grand total is: $',totalAmount + 8)
elif hundredFifty:
print('Your shipping is: $10.00')
print('Your grand total is: $',totalAmount + 10)
elif twoHundred:
print('Your shipping is free!')
print('Your grand total is: $',totalAmount)

if Country == "Canada":
if lessFifty:
print('Your shipping is: $8.00')
print('Your grand total is: $',totalAmount + 8)
elif fiftyHundred:
print('Your shipping is: $10.00')
print('Your grand total is: $',totalAmount + 10)
elif hundredFifty:
print('Your shipping is: $12.00')
print('Your grand total is: $',totalAmount + 12)
elif twoHundred:
print('Your shipping is free!')
print('Your grand total is: $',totalAmount)

endProgram = input ('Do you want to restart the program?')
if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'):
break

最佳答案

这是简化代码的核心。它打印美国 100.00 美元的运费

totalAmount = 100

chargeCode = (int(100*(totalAmount+0.001))-1)/5000 #0 -- <=50, 1 -- 50.01-100, etc
if chargeCode > 3: chargeCode = 3

shipping = {}
shipping[("USA", 0)] = 6
shipping[("USA", 1)] = 8
shipping[("USA", 2)] = 10
shipping[("USA", 3)] = 0
shipping[("Canada", 0)] = 8
shipping[("Canada", 1)] = 10
shipping[("Canada", 2)] = 12
shipping[("Canada", 3)] = 0

print shipping[("USA", chargeCode)]

totalAmount+0.001 用于避免玩 float :

int(100*(81.85)) == 8184

在我的系统上返回 True,因为 float 81.85 比十进制 81.85 小一点。

关于Python:我可以做些什么来精简我的 Python 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14618584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com