Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从函数打印?_Python_Python 3.x_Function_Python 3.6_User Defined Functions - Fatal编程技术网

Python 如何从函数打印?

Python 如何从函数打印?,python,python-3.x,function,python-3.6,user-defined-functions,Python,Python 3.x,Function,Python 3.6,User Defined Functions,当我跑的时候,我想到了这个: 回溯(最近一次呼叫最后一次): 文件“/home/tdr/Desktop/run.py”,第11行,在 你好(姓名) 名称错误:未定义名称“name” 为什么我不能打印它?当您调用hello(name)时,name需要是代码中其他地方定义的变量。只要看看你得到的错误: def hello(name): name = ["John", "Marius", "Gica"] print(name) hello(name) Python正在四处寻找,试

当我跑的时候,我想到了这个:

回溯(最近一次呼叫最后一次):
文件“/home/tdr/Desktop/run.py”,第11行,在
你好(姓名)
名称错误:未定义名称“name”
为什么我不能打印它?

当您调用
hello(name)
时,
name
需要是代码中其他地方定义的变量。只要看看你得到的错误:

def hello(name):
    name = ["John", "Marius", "Gica"]
    print(name)

hello(name)
Python正在四处寻找,试图了解
name
的含义。但它找不到定义,所以产生了错误。您需要使用特定的值调用函数,例如,以下操作将起作用:

hello(name)
NameError: name 'name' is not defined
或者您可以使用已在其他地方定义的变量调用函数。因此,以下措施也将起作用:

hello("John")

如果您不打算在函数中使用参数,那么让函数不带参数就更有意义了:

myName = "Ismael"
hello(myName)
如果要从列表中随机选择项目,可以使用:


打印作为参数传递的名称,除非它是
None
或空的

import random

def hello():
    name = ["John", "Marius", "Gica"]
    chosenName = random.choice(name) # this chooses a random name from the list
    print( chosenName )

hello()

如果您想使上述解决方案更加优雅,可以编写
如果不是name:
而不是
如果name是None或name是“”
,因为空字符串在Python中是错误的。

请告诉我import random代表什么?没有它,它能工作吗?实际上,我打算使用参数创建一个函数,它接受一个字符串参数并返回Hello
random
是我们导入以利用
random.choice()
的库。这是从序列中选择随机项的正常方法,没有它,此特定解决方案将无法工作。您可以阅读更多有关
random
[文档中]的信息。如果name为空或无,请返回Hello,World!如果要打印作为参数接收的函数,请创建一个带有参数(
def Hello(name)
)的函数。检查
name
是否为无(
如果name为无:
),然后打印
Hello,World
或作为参数传递的名称(
print(“Hello,+name)
)。
import random

def hello():
    name = ["John", "Marius", "Gica"]
    chosenName = random.choice(name) # this chooses a random name from the list
    print( chosenName )

hello()
def hello(name):
    if name is None or name is "":
        print("Hello, World!")
    else:
        print("Hello, " + name + "!")

hello("")     # Hello, World!
hello("John") # Hello, John!