简体   繁体   English

如何将参数传递给函数

[英]How passing an argument to a function

Why doesn't this work? 为什么不起作用? What would it take for this to work? 这项工作需要什么?

call = 'Duster'
def text(call):
    print(call)

text()

The call inside your function and call outside your function are utterly independent variables. 你的功能之外的功能和呼叫内的通话是完全独立的变量。 You have to pass things through the parameter list. 您必须通过参数列表传递内容。

call = 'Duster'
def text(call):
    print(call)

text(call)

Actually, you can use a global variable, but please avoid those. 实际上,您可以使用全局变量,但请避免使用这些变量。

To illustrate this better, move the lines of your main program together and change the names: 为了更好地说明这一点,将主程序的各行移到一起并更改名称:

def text(phrase):
    print(phrase)

name = 'Duster'
text(name)

Also, the main program of two lines could be just one line: 另外,两行的主程序可能只是一行:

text('Duster')

It doesn't work because the argument named call takes precedence over the variable named call due to scoping. 这是行不通的,因为参数命名call的优先级高于命名变量call由于作用域。

You could make this work by using your code and just changing the last line 您可以通过使用代码并更改最后一行来完成这项工作

text(call)

Or you could use the variable directly and not an argument 或者您可以直接使用变量而不是参数

call = 'Duster'
def text():
    print(call)

text()

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

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