开发者

python indentation

开发者 https://www.devze.com 2023-02-05 00:20 出处:网络
I am trying to make this script work but it\'s... giving me indentation errors #开发者_如何学C!/usr/bin/env python

I am trying to make this script work but it's... giving me indentation errors

#开发者_如何学C!/usr/bin/env python
import io

myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('|')[0]
try:
    myfile.write('blah')
finally:
        myfile.close()
except IOError:

Help?


Try-except-finally statement has the following syntax:

try:
    statement 1
except:
    statement 2
finally:
    statement 3

You're doing it a little bit wrong :) Try to fix)

Also, as Herohtar said, swap your finally and except statements. Finally really should go after except.


try:
    myfile.write('blah')
finally:
        f.close()
        except IOError:
myfile.close()

Why is the except IOError at the same indent level as f.close? Reading the code, it seems to me that it should look like

try:
    myfile.write('blah')
except IOError:
        myfile.close()
finally:
        f.close()

Also, I think that you mean myfile.close instead of f.close.


Your Finally is indented two tabs.

Also, make sure you're not combining spaces and tabs.

Looking more at the code:

Your except should be on the same level as the Try/Finally, and needs an indented block after.

Why f.close? There's no f.open.

0

精彩评论

暂无评论...
验证码 换一张
取 消