The good/old control statements – if

if statement has 3 keywords only and a straightforward syntax:

if <cond-1>:
     <stat-1>
elif <cond-2>:
     <stat-2>
else:      <stat-n>

Conditions seem to be ending with ':'. 'else' is a condition also here – "otherwise". like default of switch.


Letting the following equally work:

if x < 0: x = 0; print('Negative changed to zero')
elif x == 0: print('Zero')
elif x == 1: print('Single')
else: print('More')


as well as

if x < 0:
     x = 0
     print('Negative changed to zero')
elif x == 0:
     print('Zero')
elif x == 1:
     print('Single')
else:
     print('More')


Note ';' as line separators between same-level/inner statements. So – `;` and line-separator seem to be  equivalent at such use (?) Mental note - see whether this is accurate, and can generalize this to their other/all use.

The following is an error thou. Looks like merely the syntax of if-statement and nothing else:

if x < 0: x = 0; print('Negative changed to zero') else: print('More')

Neither is the following – ';' isn't a substitute for line separator here:

if x < 0: x = 0; print('Negative changed to zero'); else: print('More')

The way it seems, ';' stands for line separator only in between the statements of the same inner-most code block. (?)

The source i look up for this article was https://docs.python.org/3/tutorial/controlflow.html#if-statements.

Comments

Popular posts from this blog

Python - what for?

Intro

..And the very first step