Python 期望 DEDENT 的错误“不匹配的输入”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4639556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error "mismatched input" expecting DEDENT
提问by pandoragami
Following this tutorialI got the following error where y = 1; I'm using Netbeans 6.5 for Python. thanks
按照本教程,我得到以下错误,其中 y = 1; 我将 Netbeans 6.5 用于 Python。谢谢
y=1
^
SyntaxError: line 8:3 mismatched input '' expecting DEDENT (temperatureconverter.py, line 8)
SyntaxError: line 8:3 mismatched input '' expected DEDENT (temperatureconverter.py, line 8)
the following is the python code, format it for me thanks.
以下是python代码,请帮我格式化,谢谢。
__author__="n"
__date__ ="$Jan 9, 2011 3:03:39 AM$"
def temp():
print "Welcome to the NetBeans Temperature Converter."
y=1
n=0
z=input("Press 1 to convert Fahrenheit to Celsius, 2 to convert Celsius to Fahrenheit, or 3 to quit:")
if z!=1 and z!=2 and z!=3:
e=input("Invalid input, try again?(y or n)")
if e==1:
t=''
temp()
if e==0:
t="Thank you for using the NetBeans Temperature Converter."
print "Celsius Fahrenheit" # This is the table header.
for celsius in range(0,101,10): # Range of temperatures from 0-101 in increments of 10
fahrenheit = (9.0/5.0) * celsius +32 # The conversion
print celsius, " ", fahrenheit # a table row
temp()
采纳答案by Amnon
In the printstatement you used 2 spaces to indent the line, while in the next one you put 3 spaces.
在该print语句中,您使用了 2 个空格来缩进该行,而在下一个中,您使用了 3 个空格。
Whitespace is significant in Python. Specifically, if you have a certain level of indentation in one line you can't just use another one for the next line.
空格在 Python 中很重要。具体来说,如果您在一行中有一定程度的缩进,则不能只在下一行使用另一个缩进。
回答by pandoragami
Nevermind the problem went away with the complete code. sorry
没关系,问题随着完整的代码消失了。对不起
def temp():
print "Welcome to the NetBeans Temperature Converter."
y=1
n=0
z=input("Press 1 to convert Fahrenheit to Celsius, 2 to convert Celsius to Fahrenheit, or 3 to quit:")
if z!=1 and z!=2 and z!=3:
e=input("Invalid input, try again?(y or n)")
if e==1:
t=''
temp()
if e==0:
t="Thank you for using the NetBeans Temperature Converter."
if z==1: # The user wishes to convert a temperature from Fahrenheit to Celsius
x=input("Input temperature in Fahrenheit:")
t=(x-32)/1.8
print "The temperature in Celsius is:"
if z==2: # The user wishes to convert a temperature from Celsius to Fahrenheit
x=input("Input temperature in Celsius:")
t=(x*1.8)+32
print "The temperature in Fahrenheit is:"
if z==3: # The user wishes to quit the application
t="Thank you for using the NetBeans Temperature Converter."
print t
if z==1 or z==2:
a=input("Do you want to perform another conversion?(y or n)")
if a==0:
t="Thank you for using the NetBeans Temperature Converter."
if a==1:
t= ''
temp()
print t
temp()
回答by Hugh Bothwell
For interest's sake here is an extended version of the example. I have incorporated a certain amount of magic which may lead you to a deeper understanding of Python!
出于兴趣,这里是示例的扩展版本。我已经加入了一定的魔法,可以让你更深入地了解 Python!
And - as I am always glad to continue learning - does anyone else have suggestions on how this ought to be be extended and improved in a correctly Pythonic manner?
而且 - 因为我总是很高兴继续学习 - 有没有其他人对如何以正确的 Pythonic 方式扩展和改进它有任何建议?
class MenuItem(object):
def __init__(self, fn, descr=None, shortcuts=None):
"""
@param fn: callable, callback for the menu item. Menu quits if fn returns False
@param descr: str, one-line description of the function
@param shortcuts: list of str, alternative identifiers for the menu item
"""
if hasattr(fn, '__call__'):
self.fn = fn
else:
raise TypeError('fn must be callable')
if descr is not None:
self.descr = descr
elif hasattr(fn, '__doc__'):
self.descr = fn.__doc__
else:
self.descr = '<no description>'
if shortcuts is None:
shortcuts = []
self.shortcuts = set(str(s).lower() for s in shortcuts)
def __str__(self):
return self.descr
def hasShortcut(self,s):
"Option has a matching shortcut string?"
return str(s).lower() in self.shortcuts
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)
class Menu(object):
def __init__(self):
self._opts = []
def add(self, od, *args, **kwargs):
"""
Add menu item
can be called as either
.add(MenuItem)
.add(args, to, pass, to, MenuItem.__init__)
"""
if isinstance(od, MenuItem):
self._opts.append(od)
else:
self._opts.append(MenuItem(od, *args, **kwargs))
def __str__(self, fmt="{0:>4}: {1}", jn='\n'):
res = []
for n,d in enumerate(self._opts):
res.append(fmt.format(n+1, d))
return jn.join(res)
def match(self, s):
try:
num = int(s)
if 1 <= num <= len(self._opts):
return self._opts[num-1]
except ValueError:
pass
for opt in self._opts:
if opt.hasShortcut(s):
return opt
return None
def __call__(self, s=None):
if s is None:
s = getStr(self)
return self.match(s)
def fahr_cels(f):
"""
@param f: float, temperature in degrees Fahrenheit
Return temperature in degrees Celsius
"""
return (f-32.0)/1.8
def cels_fahr(c):
"""
@param c: float, temperature in degrees Celsius
Return temperature in degrees Fahrenheit
"""
return (c*1.8)+32.0
def getFloat(msg=''):
return float(raw_input(msg))
def getStr(msg=''):
print(msg)
return raw_input().strip()
def doFahrCels():
"Convert Fahrenheit to Celsius"
f = getFloat('Please enter degrees Fahrenheit: ')
print('That is {0:0.1f} degrees Celsius'.format(fahr_cels(f)))
return True
def doCelsFahr():
"Convert Celsius to Fahrenheit"
c = getFloat('Please enter degrees Celsius: ')
print('That is {0:0.1f} degrees Fahrenheit'.format(cels_fahr(c)))
return True
def doQuit():
"Quit"
return False
def makeMenu():
menu = Menu()
menu.add(doFahrCels, None, ['f'])
menu.add(doCelsFahr, None, ['c'])
menu.add(doQuit, None, ['q','e','x','quit','exit','bye','done'])
return menu
def main():
print("Welcome to the NetBeans Temperature Converter.")
menu = makeMenu()
while True:
opt = menu()
if opt is None: # invalid option selected
print('I am not as think as you confused I am!')
else:
if opt() == False:
break
print("Thank you for using the NetBeans Temperature Converter.")
if __name__=="__main__":
main()
回答by 42n4
Use Preferences->Pydev->Editor and uncheck replace tabs with spaces. Tabs can be 4 spaces despite popular opinion that it should be changed to 8 spaces. It removes all detent errors.
使用 Preferences->Pydev->Editor 并取消选中用空格替换制表符。尽管普遍认为应该将制表符更改为 8 个空格,但制表符可以是 4 个空格。它消除了所有定位错误。
回答by MarkyMarksFunkyBunch
Yea this is what did it for me. I was playing around in Notepad++ with a .py file that was made in Eclipse, Eclipse was using spaces and I was using tabs. It looked the same as 4 spaces = 1 tab so I just used spaces instead of tabs and all was well.
是的,这就是为我所做的。我在 Notepad++ 中玩弄一个在 Eclipse 中制作的 .py 文件,Eclipse 使用空格而我使用制表符。它看起来与 4 个空格 = 1 个制表符相同,所以我只使用空格而不是制表符,一切都很好。

