Professional Documents
Culture Documents
Module01 wk01c ControlFlows
Module01 wk01c ControlFlows
Structures
Networking for Software Developers
Narendra Pershad
Objectives
Explore how python expects code block
Sequential or sequence:
Each line is process exactly once with no skips
Conditionals or branching:
Blocks of code that may be processed optionally
All the statements that is to be part of that block must be indented by the same amount
If a line is outdented, that this signal that the previous block has completed
If you don’t have a statement for a block, then you must use the keyword pass
if test1: # if test
statement1 # associated block
elif test2: # optional elifs
statement2
else # optional else
statement3
>>> temp = 98
>>> if temp < 98:
... print('Cold')
... elif temp > 98:
... print('Hot')
... else:
... print('Normal')
...
Normal
The while loop
You may use the break and continue statements in both the while and the for
loop
>>> sum
4950 #sum of the integers up to 100
>>> x = 0
>>> while True:
... print(f'{x}', end=' ')
... x += 1
... if x > 5:
... break
0 1 2 3 4 5
The for loop
>>> sum
15 #sum of the number in the list a
Using the range method
>>> lst
[1, 2, 3, 4, 5]
>>> for x in range(10) :
... if x % 2 == 0:
... continue
... print(f'{x}', end=' ')
...
...
1 3 5 7 9
>>> a = 'Programming I'
>>> for x in a:
... print(f'{x}', end=' ')
...
P r o g r a m m i n g I
>>> distros = ['ubuntu', 'redhat', 'centos']
>>> arch = ['32-bit', '64-bit']
>>> for d in distros:
... for a in arch:
... print(d + ' ' + a)
... print('------------')
...
ubuntu 32-bit
ubuntu 64-bit
------------
redhat 32-bit
redhat 64-bit
------------
centos 32-bit
centos 64-bit
------------
The Ternary operator
Syntax:
«statement_if_true» if «assertion» else «statement_if_false»
>>> temp = 97
>>> print('Cold') if temp < 98 else print('Normal')
Cold
Summary
As with all programming languages, python has the usual control structures
Sequence
Programs can complete a single task
Conditional
Programs can complete multiple tasks
Looping
Write less code to do the same thing
Functions
Developer more production, because code can be reuse