【问题标题】:Why does this function only compute with python 3?为什么这个函数只用 python 3 计算?
【发布时间】:2018-06-28 01:05:01
【问题描述】:
def monthly_gas_cost(days,miles,mpg,gas_cost):
    return '${} A month for gas'.format(miles/mpg*days*gas_cost)

我在python中做了一个简单的函数,刚刚使用python没有思考,它已经与

print(monthly_gas_cost(days=23,miles=4,mpg=30,gas_cost=2.87))

但是当我尝试下面的行时,它只使用 python 3 进行计算。使用 python 2 它不计算。

print(monthly_gas_cost(days=23,miles=12,mpg=20,gas_cost=2.87))

【问题讨论】:

  • "它只适用于 python 3" --- 这到底是什么意思?在python 2.7下运行你的电脑会关机吗?
  • @zerkms 没有完成计算
  • “没有完成计算”的意思是“永远冻结”,而你观察到的东西肯定不同。清楚地解释问题也有助于您从一开始就理解问题。

标签: python-3.x python-2.7 function


【解决方案1】:

这是因为 Python 2 中的除法行为不同,所以使用

from __future__ import division

在您的 Python 2 代码中

【讨论】:

  • 特别是,在 Py2 中,除法运算符 / 取决于类型,如果分子和分母都是 ints,那么它会进行整数除法。在 Py3 中,这不再适用,/ 始终是浮点除法,您需要使用显式整数除法运算符 //from __future__ ... 为 Py2 带来了 Py3 的行为。
猜你喜欢
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 2017-04-11
相关资源
最近更新 更多