我在标题中定义了问题 哎呀
我尝试了很多东西,我什至无法全部写出来。
def document(title="cool", genre="fiction"):
print(title+genre)
document(title = "once upon a time ")
document(“awesome”)
document(title+genre)
我希望它能印刷,从前很棒,很酷的小说。
您定义了一个函数,该函数接受名为title
和genre
的两个参数。这两个参数只能在函数中作为局部变量访问。由于这些变量未在函数外部声明,因此无法访问它们。
def document(title="cool", genre="fiction"):
print(title+genre)
#declaration of variables
title="foo"
genre="bar"
document(title, genre)
def document(title="cool", genre="fiction"):
这意味着该函数有两个参数,分别名为title
和genre
。其中每个都提供了一个默认值,如果调用方不提供它们,则将填写该默认值。这不是以您似乎正在考虑的方式"定义title
"。每个函数都有自己完全独立的事物名称集,以及事物的全局名称集。
print(title+genre)
这意味着无论提供什么值,无论它们来自调用方还是默认值,都将连接并打印。
document(title = "once upon a time ")
这表示调用函数并使用"once upon a time "
作为title
的值。未提供genre
的值,因此打印默认值"fiction" is used. Thus,
从前小说'。
document("awesome")
这表示调用函数并使用"awesome"
作为第一个参数的值。该参数是title
参数,因此"awesome"
用作title
的值。和以前一样,genre
的值仍然是"fiction"
的,所以awesomefiction
被打印出来。
请注意,当函数运行时,title
是函数用于字符串"awesome"
的名称,即使您在调用函数时没有说明title
。
document(title+genre)
这表示使用调用上下文中title
和genre
的任何值作为第一个参数的值。但是在函数之外没有这样的定义名称。函数的参数是完全独立的,在这里没有任何意义。您得到一个NameError
,因为没有定义有问题的名称。
你对定义一个变量感到困惑(例如title = "once upon a time"
(,并指定函数参数document(title="whatever")
。后者只指定传递给函数document()
参数,它没有定义一个名为title
的局部变量。
在括号内"的意思是"在我的函数调用中document()
">
一种解决方案是执行以下操作:
title = "once upon a time " # <-- actually define a local variable
genre = "Mongolian puppetry"
document(title) # now you can use that variable in your function call
document(“awesome”)
document(title+genre) # ...and reuse that variable again