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

标签 python

我可以用不同的代码来简化这个 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/

相关文章:

python - 尝试创建带有锁定的简单按钮推送播放

python - 如何更改图像的不透明度并在 Python 中与另一个图像合并

python - 从噪声值列表中计算 "near multiplicity"的度量

python - 在 Flask 模板中渲染 html 字符串

python - 使用 Tkinter 进行线程化

python - django-filter如何向表单下的html标签添加属性

cmd 路径上的 Python

python - 创建字符串行,其中行数等于列表中的元素数

Python 数组与列表

Python Pandas Group By 错误 'Index' 对象没有属性 'labels'