【问题标题】:why Python isn't completing the def statement? [closed]为什么 Python 没有完成 def 语句? [关闭]
【发布时间】:2021-01-01 17:42:11
【问题描述】:

我仍在使用 Python 开始我的旅程,所以这是一个我不明白的简单问题。

尝试从这里使用 Ziggy 对 Cramer 的 V 统计量的定义声明: Using pandas, calculate Cramér's coefficient matrix

但是当我将它放入 Python 时,定义并没有在返回处结束:

>>> import pandas as pd
>>> def cramers_corrected_stat(confusion_matrix):
...     # calculate Cramers V statistic for categorial-categorial association.
...     # uses correction from Bergsma and Wicher,
...     # Journal of the Korean Statistical Society 42 (2013): 323-328
...
...     chi2 = ss.chi2_contingency(confusion_matrix)[0]
...     n = confusion_matrix.sum()
...     phi2 = chi2/n
...     r,k = confusion_matrix.shape
...     phi2corr = max(0, phi2 - ((k-1)*(r-1))/(n-1))
...     rcorr = r - ((r-1)**2)/(n-1)
...     kcorr = k - ((k-1)**2)/(n-1)
...     return np.sqrt(phi2corr / min( (kcorr-1), (rcorr-1)))
...

我没看到什么?

【问题讨论】:

  • 再次按 Enter。
  • 如果您正在编写大型函数,那么编写一个脚本可能会更容易。
  • (在正常的交互环境中,Python 会在第一个空行之后停止并抛出 SyntaxError。要么你无意中改变了你向我们展示的脚本,要么你正在使用其他的奇怪的环境。)

标签: python indentation definition


【解决方案1】:

当你在 REPL 中时,你需要两个连续的空行来完成语句。但是在 REPL 中编写代码非常麻烦,因为您无法轻松编辑/修复以前编写的代码,因此我建议您将所做的任何事情保存到 .py 文件中,您可以在其中更轻松地编辑代码然后运行代码来自python ./myfile.py

【讨论】:

  • 一个空行就够了。
  • (或者至少应该是 - 我同意 user2357112 支持 Monica 对 OP 没有正确报告的怀疑)
猜你喜欢
  • 2021-02-12
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2014-08-25
  • 2015-11-13
  • 1970-01-01
  • 2017-09-22
  • 2013-06-21
相关资源
最近更新 更多