Python 3.x 为什么函数代码不起作用
我试图得到一个函数调用,但我不能得到它打印。请帮忙。 代码如下:Python 3.x 为什么函数代码不起作用,python-3.x,functional-programming,Python 3.x,Functional Programming,我试图得到一个函数调用,但我不能得到它打印。请帮忙。 代码如下: def foo(): name = input ('>>').lower().split() for item in name: if name == foo: print ('foo here!') else: bar() def bar(): name = input ('>>').lower().split()
def foo():
name = input ('>>').lower().split()
for item in name:
if name == foo:
print ('foo here!')
else:
bar()
def bar():
name = input ('>>').lower().split()
for item in name:
if name == bar:
print ('bar here!')
def start():
print('Welcome Home')
name = input
foo()
start()
print('foo here!')
和print('bar here!')
都不会执行,因为布尔表达式name==foo
和name==bar
在大多数情况下计算为false。例如,在定义foo()
下的布尔表达式name==foo
中,将列表name
的第一个元素与foo
进行比较foo
返回对象函数的友好字符串表示形式foo()
(通常用于调试目的)。实际上,您可以通过执行print(foo)
来尝试打印foo()
,并将返回值分配给foo()
中的列表name
(在我的例子中,它的
,在您的机器中可能会有所不同)。这将把name==foo
计算为true,因此将导致执行print('foo here!')
。话虽如此,但:
名称
列表中的第一个元素分配给项
变量。接下来,执行for循环的主体。执行主体后,在再次执行for循环主体之前,列表name
中的第二个元素被分配给变量item
。此过程将继续,直到名称
列表中没有更多元素为止。现在,为了执行sayprint('foo here!')
,if语句中的布尔表达式必须计算为true
下面是一个示例,当用户在运行程序后键入foo时,将执行print('foo Here!')
def foo():
name = input('>>').lower().split()
for item in name:
if item == 'foo':
print('foo here!')
else:
bar()
def bar():
name = input('>>').lower().split()
for item in name:
if item == 'bar':
print('bar here!')
print('Welcome Home')
foo()
在定义foo()
中,将列表name
的第一个元素与foo进行比较,从而满足条件if name==“foo”
。以下是执行的示例:
[firas@arch Python]$ ./foobar.py
Welcome Home
>>foo
foo here!
你想让它做什么?仅仅通过阅读代码,我会说“if name==foo”可能不是您想要的(在foo的定义中),它将“name”(一个字符串列表)与“foo”(一个函数对象)进行比较,而这两个值永远不会相等。