如何调用另一个功能(温度)作为主要功能

时间:2018-06-30 10:13:13

标签: python python-3.x

我正在输入示例代码。我将温度定义为主要功能,但无法运行它。它自动关闭,没有任何输入提示。

def temperature():
    number = input('Enter what you want\n')
    values = number.split(' ')
    temperature = values[0]
    unitin = values[1]
    unitout = values[-1]
    print(temperature, 'this', unitin, 'is', unitout, 'working')  # this is working is a test statemment i was unsure
    print('This is a test function', number)


def main():
    temperature()


if __name__ == "__main__":
    main()

这是运行的代码的一部分。但是,一旦我尝试仅更改主要功能的名称,它便停止工作。我不确定,它仅使用名称“ main”吗?

def readinput():
input_string = input('Enter what you want\n')
values = input_string.split(' ')
temperature = values[0]
unitin = values[1]
unitout = values[-1]
print(temperature, 'this', unitin, 'is', unitout, 'working')
print('This is a test function', input_string)


def temperature_converter():
    readinput()


if __name__ == "__temperature_converter__":
    temperature_converter()

这是无效的代码。谢谢。

2 个答案:

答案 0 :(得分:2)

如果您自己运行代码,则解释器会自动将变量__name__设置为"__main__"。这与您的函数名称无关。看看What does if __name__ == "__main__": do?

这应该有效:

if __name__ == "__main__":
    temperature_converter()

答案 1 :(得分:0)

如果模块使用功能{{1单独运行(而不是由另一个模块导入),则将包含字符串__name__的特殊变量'__main__'的内容弄混了}} –这些完全无关的事情,当您将函数main()的名称更改为其他名称时,请直接保留字符串main()

或者您可以完全删除以__main__开头的行,它也可以在没有的情况下工作。