自定义python功能不起作用

时间:2013-08-25 13:56:33

标签: python function syntax-error

我从Codecademy学习Python。

有一个问题:

编写一个函数shut_down,它接受​​一个参数(你可以使用你喜欢的任何东西;在这种情况下,我们使用s作为字符串)。 shut_down函数在'Shutting down...''Yes''yes'作为参数时会返回'YES''Shutdown aborted!'到达'No''no' 1}},'NO'def shut_down(n): p=n.lower() if p=="yes": return "Shutting down..." elif p=="no": return "Shutdown aborted!"

为此,我写了这个:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'yes' is not defined*

但是,当我尝试运行它时,会发生以下错误:

{{1}}

请帮助我......我的代码中是否存在某种错误?

2 个答案:

答案 0 :(得分:3)

由于您没有包含第1行(错误行),因此很难确切知道发生了什么。但是,从我个人的经验来看,我认为你的问题是两件事之一:

1)当您使用input时,您使用的是Python 2.x并使用raw_input

>>> input()
yes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'yes' is not defined
>>> raw_input()
yes
'yes'
>>>

2)如果您应该yes,则在第一行有'yes'

>>> yes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'yes' is not defined
>>> 'yes'
'yes'
>>>

在这两种情况下(以及我错过的任何一种情况),您将“是”视为已定义的变量而不是字符串。

答案 1 :(得分:1)

上面的代码工作正常。可能问题是,在您调用该函数时,您使用的是shut_down(yes)而不是shut_down('yes')