开发者

Executing Multiple Lines in Python

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 tr开发者_运维问答ied to run the above code, I got an invalid syntax error on ELSE


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'


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.


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.


print n % 2 == 0 and 'Even' or 'Odd'

:-)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜