简体   繁体   English

你如何在python中调用一个函数?

[英]How do you call a function in python?

Ok guys, this is driving me crazy.好吧,伙计们,这让我发疯。 I know java, but python is nuts.我知道 java,但 python 很疯狂。 I'm just trying to writing a simple counter program using a for loop, but I can't do that because this language is made for weirdos.我只是想用 for 循环编写一个简单的计数器程序,但我不能这样做,因为这种语言是为怪人设计的。 Haha, ok just kidding on that one, but seriously, what am I doing wrong?哈哈,好吧,开个玩笑,但说真的,我做错了什么?

class makeLines:
    def main():
       counter()
        
    def counter():
        for i in range(0,10):
            print(i)

When I run it, nothing happens.当我运行它时,什么也没有发生。 No output...没有输出...

You call functions in Python exactly as in Java:您可以像在 Java 中一样在 Python 中调用函数:

function_name(args…)

Your code doesn't work because its indentation is broken.您的代码不起作用,因为它的缩进被破坏了。 Furthermore, there is no global code calling any function.此外,没有调用任何函数的全局代码。 Unlike Java, Python code doesn't have to be inside classes, and there is no entry point.与 Java 不同,Python 代码不必在类内部,并且没有入口点。 Just call the function directly:直接调用函数即可:

def counter():
    for i in range(0,10):
        print(i)
        
counter()

You can create an entry point function, and this is in fact often a good idea.可以创建一个入口点函数,这实际上通常是一个好主意。 So you will see a lot of code in Python that looks as follows :所以你会在 Python 中看到很多如下所示的代码:

import sys


def main():
    ‹main logic here›


if __name__ == '__main__':
    sys.exit(main())

The reason for this is to make code usable as both a module and an executable .这样做的原因是使代码既可用作模块又可用作可执行文件

Erase your first and second lines, because you don't need any classes and main() function(it's not C++ or Java, there's no such thing like main function in Python) in that case.删除你的第一行和第二行,因为在这种情况下你不需要任何类和 main() 函数(它不是 C++ 或 Java,Python 中没有像 main 函数这样的东西)。 And you must add the space before your 'for' loop.并且您必须在“for”循环之前添加空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM