indentation blocking in Python

A

ajetrumpet

hello all,

This has got me a tad bit confused I think. I am running 3.3.0 and I know that Python looks to group code together that is supposed to be in the sameblock. But the question is, where are the rules for this? For instance, if I type the following in a PY file, it errors out and I don't see the DOSwindow with the output in Vista:

a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")

However, if I don't indent anything at all, it works!

a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")

Can someone offer just a little explanation for this? 'IF' and 'ELSE' are obviously in the same code block. Are they not? Maybe it's not so obvious.. Thanks.
 
C

Colin J. Williams

a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")
You indent only subordinate statements.

You don't need a semi-colon unless it separates two statements on the
same line.

Your code:

a=1
if a==1:
print(1)
else:
print(0)
wait = input("press key")

I hope that this helps.

Colin W.
 
C

Chris “Kwpolska†Warrick

hello all,

This has got me a tad bit confused I think. I am running 3.3.0 and I know that Python looks to group code together that is supposed to be in the same block. But the question is, where are the rules for this? For instance, if I type the following in a PY file, it errors out and I don't see the DOS window with the output in Vista:

It’s called the command prompt.
a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")

However, if I don't indent anything at all, it works!

a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")

You indented the wrong thing. You put your if/else statement in a
non-standard way (which works, but is discouraged). Also, you ended
the first line with a semicolon (same case). So, the proper code
would be:

a=1
if a==1:
print(1)
else:
print(0)
wait = input("press key")

(I resisted the urge to add spaces around `=` and `==`, something most
people want you to do.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top