代码在编辑器上运行良好,但在 Code Wars 中出现 EOF 错误

时间:2021-04-27 16:29:56

标签: python

我是编程新手,一天前刚加入 Code Wars。所以我有一个名为“Alan Partridge II - Apple Turnover”的 Kata。

它基本上告诉我这样做: “你的工作很简单,如果(x)的平方大于1000,就返回'比太阳还热!!',否则,返回 “帮自己买一个蜂窝约克犬的手套箱。”。 X 将是一个有效的整数。 X 将是一个数字或一个字符串。两者都是有效的。”

这是我写的代码:

import math
def apple(x):
    if math.sqrt(x)>=1000:
        print("It's hotter than the sun!!")
    else:
        print("Help yourself to a honeycomb Yorkie for the glovebox.")
apple(x=int(input("gimme a temp\n")))

当我在 Pycharm 上尝试时,我很确定一切正常。但是当我在 Code Wars 上对其进行测试时,发生了这种情况:

Log
gimme a temp
STDERR
Traceback (most recent call last):
  File "tests.py", line 2, in <module>
    from solution import apple
  File "/workspace/default/solution.py", line 7, in <module>
    apple(x=int(input('gimme a temp')))
EOFError: EOF when reading a line

这是我的测试结果截图: Here is the screenshot of my test results

由于我是新来的,我不确定发生了什么。

谁能帮我找出问题所在?

1 个答案:

答案 0 :(得分:3)

看起来 Code Wars 将函数导入到自己的代码中,然后运行它。问题是当导入一个函数时,Python 会运行你的整个文件。它可能不希望您运行 input() 函数。您可以通过将自己的函数调用放在 if __name__== "__main__": 语句中来解决这个问题:

import math
def apple(x):
    if math.sqrt(x)>=1000:
        print("It's hotter than the sun!!")
    else:
        print("Help yourself to a honeycomb Yorkie for the glovebox.")
if __name__ == "__main__":
    apple(x=int(input("gimme a temp\n")))

if 语句基本上检查您是在运行文件本身,还是从另一个 Python 脚本导入它。因此,当 Code Wars 尝试验证您的函数时,它会导入它而不执行您自己的函数调用。