简体   繁体   English

python中的函数-需要说明

[英]functions in python - need explanation

can someone simply explain functions in python? 有人可以简单地解释python中的功能吗? I just can't get my head around them. 我只是无法理解他们。

So I have had a go at them, and this is what I've ended up with, but it keeps saying that character is not a global variable 所以我尝试了一下,这就是我最后得到的结果,但它一直说字符不是全局变量

def char_name():
    character = input("Enter character name: ")
    return character;


def main():
    char_name()
    print(character)


main()

Can anyone explain functions? 谁能解释功能?

This part is a function: 这部分是一个功能:

def char_name():
    character = input("Enter character name: ")
    return character;

It's important to realize that the variable character exists only inside the function. 要认识到,变量是很重要的character存在, 在函数内部。 Not outside of it. 不在外面。 That's a great feature -- it means that if you decide that name is a better name for the variable after all, then you only need to change the variables inside the function, and guaranteed nowhere else. 这是一个很棒的功能-这意味着,如果您认为该name毕竟是变量的更好名称,那么您只需要更改函数内的变量,就可以保证别无其他。 No assignments to variables elsewhere can influence what happens in your function. 任何其他地方的变量赋值都不会影响函数中发生的事情。 It's all there. 都在那里。

The function has a return value equal to the value of the variable at the end of the function. 该函数的返回值等于该函数末尾的变量值。

def main():
    char_name()
    print(character)

And here's another function, that also tries to have a variable named character . 这是另一个函数,它也尝试具有一个名为character的变量。 It happens to have the same name, but that's just a coincedence, it's a different function so it's a different variable. 它恰好具有相同的名称,但这只是一个巧合,它是一个不同的函数,所以它是一个不同的变量。 Unfortunately, this variable is only used but never set to any value, and Python can't find it as a global variable either, so it throws an exception. 不幸的是,此变量仅被使用,但从未设置为任何值,Python也找不到它作为全局变量,因此它引发异常。 char_name is called, but its return value is not used for anything, so it's discarded. char_name被调用,但是它的返回值不用于任何东西,因此将其丢弃。

What you want to do is this: 您要做的是:

def main():
    name = char_name()  # I picked a different name to make my point
    print(name)

The function char_name is called, and its return value is assigned to the variable name . 调用函数char_name并将其返回值分配给变量name Now you can print it. 现在可以打印了。

def char_name():
    character = input("Enter character name: ")
    return character


def main():
    character = char_name()
    print(character)

main()

You need to assign returned values. 您需要分配返回值。

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

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