Python Conditionals And Loops

Control Flow

Control flow concerns how programs proceed in their execution to arrive a desired outcome. Programs can make choices depends on our programs structure and flow. We will examines the conditional statements and loops here.

Conditionals

A conditional statement is a programming concept that describes whether a region of code runs based on if a condition is true or false. The keywords involved in conditional statements are if, and optionally elif and else.


In [ ]:

Loops

The for statement

The for statement reads

for xxx in yyyy:

yyyy shall be an iteratable, i.e. tuple or list or sth that can be iterate. After this line, user should add an indentation at the start of next line, either by space or tab.


In [2]:
x = [1,2,3,4,5,6,7,8]
for item in x:
    print item


1
2
3
4
5
6
7
8

In [3]:
s = ['a','c','b','d','e','g','h',8]
for item in s:
    print item


a
c
b
d
e
g
h
8

Range function in python is a daily-use function in the for loop:


In [4]:
for item in range(1,20,2):
    print item


1
3
5
7
9
11
13
15
17
19

This is a simple for loop that sum up all squared integer from 1 to 100


In [5]:
s=0
for i in range(1,100):
    s+=i*i
print s


328350

The While statement

The While statement reads

while CONDITIONAL:

CONDITIONAL is a conditional statement, like i < 100 or a boolean variable. After this line, user should add an indentation at the start of next line, either by space or tab.


In [6]:
s=0; i=1
while i<100:
    s+=i*i
    i+=1
print s


328350

In [8]:
m = 20
n = 79
while n != 0:
    r = m % n
    m = n
    n = r
print m


1

In [ ]: