tags:

views:

122

answers:

4

When Python is first installed, the default setting executes users' code input line-by-line. But sometimes I need to write programs that executes multiple lines at once. Is there a setting in Python where I can change the code execution to one block at once? Thanks

>>> if (n/2) * 2 == n:;
        print 'Even';
        else: print 'Odd'

SyntaxError: invalid syntax

When I tried to run the above code, I got an invalid syntax error on ELSE

+1  A: 

One step towards the solution is to remove the semicolon after the if:

if True:; print 'true'; print 'not ok'; # syntax error!

if True: print 'true'; print 'ok'; # ok

You cannot have an else in the same line because it would be ambiguous:

if True: print 't'; if True: print 'tt; else: ... # <- which if is that else for??

It is also clearly stated in the docs that you need a DEDENT before the else statement can start.

Olivier
made some clarifications thanks
It's not actually ok at all to use semicolons after any expression;
hyperboreean
@hyperboreean: quoting the docs: "A suite can be one or more **semicolon-separated** simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines."
Olivier
@Olivier, see my answer for python >=2.5
Unreason
+8  A: 

Your indentation is wrong. Try this:

>>> if (n/2) * 2 == n:
...     print 'Even'
... else: print 'Odd'

Also you might want to write it on four lines:

>>> if (n/2) * 2 == n:
...     print 'Even'
... else:
...     print 'Odd'

Or even just one line:

>>> print 'Even' if (n/2) * 2 == n else 'Odd'
Mark Byers
A: 

Since python 2.5 you can do one line ifs

print ('Even' if n % 2 == 0 else 'Odd')

Still to answer your question you can either:
1. enter the code properly without syntax errors and your blocks will be executed as blocks regardless if they span multiple lines or not, even in interactive shell. See tutorials in dive into python
2. write code in the script and execute that script using either command line or some IDE (idle, eclipse, etc..)

One of the idea behind python is to prefer multiple lines and to aim for uniform formatting of source, so what you try to do is not pythonic, you should not aim to cram multiple statements into single line unless you have a good reason.

Unreason
A: 
print n % 2 == 0 and 'Even' or 'Odd'

:-)

Hongbo Zhu