Python定義函式報錯 return outside function

feelpurple發表於2017-07-05
在Python中定義函式時報錯 SyntaxError: 'return' outside function
>>> def testPass(cryptPass):
...     salt = cryptPass[0:2]
... dictFile = open('dictionary.txt', 'r')
  File "", line 3
    dictFile = open('dictionary.txt', 'r')
           ^
SyntaxError: invalid syntax
>>> for word in dictFile.readlines():
...     word = word.strip('\n')
...     cryptWord = crypt.crypt(word,salt)
...     if (cryptWord == cryptPass):
...         print "[+] Found Password: "+word+"\n"
...         return True
...     print "[-] Pasword Not Found.\n"
...     return False
... 
  File "", line 6
SyntaxError: 'return' outside function

報錯原因:
函式中的縮排格式有誤,第3行之後的縮排格式不正確

解決方法:
規範縮排格式

>>> def testPass(cryptPass):
...     salt = cryptPass[0:2]
...     dictFile = open('dictionary.txt', 'r')
...     for word in dictFile.readlines():
...         word = word.strip('\n')
...         cryptWord = crypt.crypt(word,salt)
...         if (cryptWord == cryptPass):
...             print "[+] Found Password: "+word+"\n"
...             return
...         print "[-] Pasword Not Found.\n"
...         return
... 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26506993/viewspace-2141634/,如需轉載,請註明出處,否則將追究法律責任。

相關文章