2011-01-09 3 views
6

다음은 tutorial이고 y = 1 인 경우 다음 오류가 발생합니다. 파이썬 용 Netbeans 6.5를 사용하고 있습니다. 감사"입력이 일치하지 않습니다"라는 오류가 발생했습니다.

 y=1 
    ^

구문 에러 : 행 8 : 3 일치하지 않는 입력 ''DEDENT 기대 (temperatureconverter.py, 8 호선)

는 다음 날 감사의 파이썬 코드, 포맷을합니다. 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

당신은 다음 하나에 당신이 3 띄어쓰기를하면서 라인을 들여이 개 공간을 사용했다.

공백은 Python에서 중요합니다. 특히, 한 줄에 일정 수준의 들여 쓰기가 있으면 다음 줄에 다른 들여 쓰기를 사용할 수 없습니다.

+0

나는 이것이 오류를 설명한다고 생각하지 않습니다. 이 경우에는'IndentationError : unexpected indent'를 얻을 것이고'SyntaxError'는 얻을 수 없습니다. –

+3

@ 팀 : OP가 파이썬의 다른 구현을 사용했다고 생각합니다. 아마도 자이 썬일까요? – 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

간단한 루프가 더 좋은 경우 왜 재귀를 사용합니까? 파이썬 재귀에서 (거의) 항상 나쁜 선택입니다 ... 그것은 천천히 또한 무한 재귀를 가질 수 없습니다! while 루프를 대신 사용하십시오. 또한 [PEP8] (http://www.python.org/dev/peps/pep-0008/)을 읽고 규칙을 따르십시오. 귀하의 경우 모든 변수 이름은 끔찍하며, 자명 한 이름을 사용하십시오. 그 코드의 대부분에서 "if ... elif..else"절을 사용하고 "if"를 단순화해야합니다. 마지막 사항 : "입력"은 모든 악의 근원이며, 전역에서 수행 할 것으로 기대하므로 대체 방법을 찾으십시오. – Bakuriu

1

여기 예제의 확장 버전이 있습니다. 나는 파이썬에 대한 더 깊은 이해를 이끌어 낼 수있는 일정량의 마법을 도입했습니다!

그리고 언제나 학습을 계속하게되어서 기쁘게 생각합니다. 다른 사람들이 어떻게 이것을 확장해야하고 정확하게 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

환경 설정 -> Pydev-> 편집기를 사용하고 공백으로 탭 바꾸기의 선택을 취소하십시오. 탭은 8 칸으로 바꿔야한다는 대중의 의견에도 불구하고 4 칸이 될 수 있습니다. 모든 멈춤 쇠 오류를 제거합니다.

0

네,이게 나를 위해했던 것입니다. 나는 이클립스에서 만든 .py 파일로 메모장에서 놀고 있었다. 이클립스는 공백을 사용하고 탭을 사용했다. 그것은 4 칸 = 1 칸과 똑같아 보였습니다. 그래서 나는 단지 칸 대신에 칸을 사용했는데 모두 좋았습니다.

관련 문제