[Tutor] small program, but I'm very confused
Kalle Svensson
kalle@lysator.liu.se
Tue Nov 5 14:43:11 2002
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
[Melissa K. Surprenant]
> I have to write a small program for class, and I'm having a terrible
> time with it. I wrote the program, and it seems to me like it should
> work, but it doesn't. I'm sure there are more errors than this, but
> right now I get an error when I try to write to the file. It says I
> have invalid syntax, with a carat point towards the file name for the
> following line: f.write('\2\n')
>
> I would appreciate any help anyone would care to offer. Thank you!
>
> Here is the code:
...
> for y in loginsList:
> re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z])(.*?)(/n)',
> '/etc/passwd')
> f.write('\2\n')
...
The thing is that Python uses indentation to determine scope. That
is, to see if some code should be executed inside or outside a for
loop, Python looks at how the code is indented.
def func1():
print "Hello",
def func2():
print "World!"
for x in range(3):
func1()
func2()
will result in the output
Hello Hello Hello World!
This means that the indentation must be consistent,
for x in range(3):
func1()
func2()
is wrong. Python can't determine if the call to func2 (which is
indented 2 spaces) should be inside (indented 4 spaces) or outside
(indented 0 spaces) the loop and instead of guessing raises a syntax
error to give you a chance to correct the code.
Peace,
Kalle
- --
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>
iD8DBQE9yB8rdNeA1787sd0RAgiBAKCz7GjPB6A0qZDj7u8Tf9DvYi3M9wCfWQ1W
8ZDDXq0ZAMvMCPJBkYWwpzw=
=bPmH
-----END PGP SIGNATURE-----