Python try except else invalid syntax?

别来无恙 提交于 2019-12-09 03:53:04

问题


So I am trying to set up a small script in Python's IDLE. The IDLE syntax check tells me this code has a syntax error:

from ftplib import FTP
import os
def ftpconnect(address, username, password):
    ftp_connection = 0
    ftp = FTP(address)
    try:
        ftp.login(username, password)
        print(ftp.getwelcome())
        if ftp.getwelcome() == '220 FTP Connected!':
            return 1
    else:
        return 0
print(ftpconnect('10.10.10.xxx', 'xxx', 'xxx'))

The syntax error comes anywhere that I try to get out of the "try" statement, here being the "else:" line. I've looked around and it seems like I have the right syntax...any thoughts?

Thanks! I'm running Python 2, not 3.


回答1:


Alright, I figured it out on my own. The problem was not with my syntax, it was with the my ftp attempt. The line that says "ftp = FTP(address)" was the one I needed to put inside a try: statement, and since I was not "try"ing it, it failed anyway. The reason I was getting a syntax error I believe is because I was using else, rather than except.



来源:https://stackoverflow.com/questions/24520523/python-try-except-else-invalid-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!