Python中的函数问题
我刚开始学习Python,正在尝试写一个非常简单的函数,但遇到了错误。我不知道为什么会这样。以下是我的示例代码:
def printme( str ):
print str;
return;
printme("My string");
这个代码本来应该能正常运行,但却给了我以下错误:
错误追踪(最近的调用在最前面):
文件 "stdin",第 1 行,在 "module"
名称错误:'printme' 这个名字没有定义
欢迎任何建议...
4 个回答
2
这个问题不工作是因为你的缩进错误。你的函数从来没有编译成功,所以它根本不存在。
(原问题已经被编辑掉,以便格式更规范)
2
遵循一下Python风格指南(pep8)可能会有帮助。虽然你不一定要这样做,但这样可以帮助你避免缩进错误,而且也能让你更容易读懂别人的代码。
5
这里的分号是不需要的,还有返回语句(函数的执行在最后一个缩进的语句处结束)。
我不太确定你是怎么格式化缩进的,但Python是依靠缩进来判断代码的范围的。
def printme(str):
print str #This line is indented,
#that shows python it is an instruction in printme
printme("My string") #This line is not indented.
#printme's definition ends before this
这样执行是正确的。
维基百科上关于 Python语法 的页面讲解了缩进的规则。