2013-10-16 26 views
1

我刚开始学习Python。我面临的问题是: 每当我在函数外部使用raw_input()时,只要在这样的函数中使用 raw_input函数,就会给我一个错误。函数中使用raw_input()的Python缩进错误

def getinput(cost): 
cost=raw_input('Enter a number ') 

它给了我一个缩进错误

回答

3

此错误与raw_input无关。但是,您可能想阅读indentation in Python。许多其他语言使用大括号(如{})来显示程序的开始和结束,或使用关键字beginend。在Python,相反,你要缩进的代码,就像这样:

def getinput(cost): 
    cost = raw_input('Enter a number ') 

所以,如果你做没有压痕,例如

def getinput(cost): 
cost = raw_input('Enter a number ') 

... Python会给你一个错误。

+0

它现在工作正常,非常感谢您的建议 – johnny

2

在Python中, “空白” 有差别。缩进级别很重要,如果不适当缩进,代码将会出错。你可以阅读更多关于Python空白here,但我会给你一个总结。

在Python中,当您运行程序时,它会通过所谓的Interpreter传递,它将您从可以理解的代码转换为您的计算机可以理解的代码。对于Python,这个解释器需要你的代码缩进,所以它知道如何转换它。每当你做一个if,else,forfunctionclass(等等),你需要增加你的缩进。

def getinput(cost): 
    cost = raw_input('Enter a number') 

以上应该工作,虽然以下不会:

def getinput(cost): 
cost = raw_input('Enter a number') 

注意第一个例子是多么的不缩进。祝你好运,学习Python!

+0

是的,你说得对,它工作正常,我刚刚在开始时增加了一个空间非常感谢 – johnny