Python 如何将脚本转换为函数
我有一个我以前写的脚本,现在正试图创建一个主页来运行这个脚本和其他脚本。我知道我必须把它转换成一个函数,然后在nesicary调用它,但是我在函数部分遇到了一些问题。非常感谢您的帮助和建议。下面是我正在引用的脚本Python 如何将脚本转换为函数,python,Python,我有一个我以前写的脚本,现在正试图创建一个主页来运行这个脚本和其他脚本。我知道我必须把它转换成一个函数,然后在nesicary调用它,但是我在函数部分遇到了一些问题。非常感谢您的帮助和建议。下面是我正在引用的脚本 #A Python math script a = float(raw_input("Enter the first number: ")) b = float(raw_input("Enter the second number: ")) print "Your answer is
#A Python math script
a = float(raw_input("Enter the first number: "))
b = float(raw_input("Enter the second number: "))
print "Your answer is: ",(a*b)
您希望函数做什么?如果您希望它仍然从提示符获取输入和输出,您可以这样做
def myfunc():
a = float(raw_input("Enter the first number: "))
b = float(raw_input("Enter the second number: "))
print "Your answer is: ",(a*b)
如果您只需要将此代码生成一个脚本,然后将其保存到一个文件中,比如multiply.py 在该文件中,您将拥有例如:
def main():
a = float(raw_input("Enter the first number: "))
b = float(raw_input("Enter the second number: "))
print "Your answer is: ",(a*b)
main()
然后您可以通过以下方式调用它:python multiply.py
您还可以通过包括这一行来检查此模块是否作为主程序执行,从而使其成为可导入模块。因此,如果它被另一个模块导入,它将不会运行
if __name__ == '__main__':
main()
在我看来,您希望能够通过webbrowser提供函数的结果,并可能以相同的方式发送查询
如果是这种情况,您可以开始。如果由于某种未知原因,您无法将其重写为其他人显示的函数,您可以这样做 Python数学脚本
#script.py
a = float(raw_input("Enter the first number: "))
b = float(raw_input("Enter the second number: "))
print "Your answer is: ",(a*b)
另一个脚本
def func():
execfile("script.py")
您真的应该看看:或者当前的文档:(v1.5文档已经有12年历史了!)您是对的。我无意中发布了一个链接,指向一个非常过时的文档谢谢,这就是我要找的。