2011-01-09 18 views
6

これに続いてtutorial私はy = 1の次のエラーが発生しました。 私はNetbeans 6.5 for Pythonを使用しています。おかげ「入力が一致しません」というエラーが発生しました。

 y=1 
    ^

にSyntaxError:行8:以下の3不一致入力 '' 期待DEDENT(temperatureconverter.py、ライン8)

は、Pythonのコード、私のためのフォーマットにそれを感謝しています。次のいずれかであなたが3にスペースを入れているときに、行をインデントするために2つのスペースを使用print声明の中で

__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() 
+0

{}ボタンを使用して、自分でフォーマットすることができます。 – Amnon

+0

コードをその中にラッピングしますか? – pandoragami

+0

いいえ、コードを選択し、 "{}"ラベルの付いたボタンをクリックします。選択したブロック全体がインデントされます。結果は、編集ボックスの下にあるプレビューウィンドウで確認できます。 – Amnon

答えて

12

空白はPythonでは重要です。具体的には、1行にあるレベルのインデントがある場合は、次の行に別のインデントを使用することはできません。

+0

私はこれがエラーを説明するとは思わない。この場合、 'IndentationError:unexpected indent'を取得し、' SyntaxError'を取得しません。 –

+3

@Tim:OPはPythonの別の実装を使用していたと思います。たぶん、Jython? – Amnon

0

問題が完全なコードでなくなってしまった。ごめんなさい

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() 
+0

シンプルなループが良いときはなぜ再帰を使用しますか? Pythonの再帰で(ほぼ)常に悪い選択です...それは遅く、またあなたは無限の再帰を持つことができません!代わりに単純なwhileループを使用します。また、[PEP8](http://www.python.org/dev/peps/pep-0008/)を読み、その規則に従ってください。あなたのケースでは、すべての変数名がひどいので、自明の名前を使用してください。そのコードのほとんどの部分では、 "if ... elif..else"節を使用し、 "if"をシンプルにする必要があります。最後のこと: "入力"はすべての悪の源であり、グローバルが行うことを期待しているので、それを行う別の方法を見つける。 – Bakuriu

1

ここでは、拡張版の例を示します。私はある程度の魔法を組み込んだので、あなたはPythonをより深く理解することができます!

そして、私はいつも勉強を続けるのがうれしくて、他の誰かがこれをどのようにして正しく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() 
0

使用Preferences-> Pydev->エディタとタブをスペースに置き換える]のチェックマークをはずします。タブは、8スペースに変更する必要があるという一般的な見解にもかかわらず、4スペースにすることができます。すべての戻り止めエラーを取り除きます。

0

これは私のためのものです。私はNotepad ++で、Eclipseで作られた.pyファイルで、Eclipseはスペースを使っていて、タブを使っていました。それは4スペース= 1タブと同じように見えたので、タブの代わりにスペースを使用して、すべてがうまくいった。

関連する問題