Python: Flow control and looping

If…else statement can be found in most mainstream programming languages to control the flow of your program’s execution. With your predescribed conditions, your program is capable of handling different circumstances by corresponding treatment. The basic syntax is:

    if condition_expression:
        statement(s)
    elif condition_expression:
        statement(s) 
    else:
        statement(s)

Both elif and else are optional and mul
tiple elif is allowed; it also provides shorthand syntax for that:

    if condition_expression: statement

or

    if condition_expression: statement else statement

Remember it, there is no curly-brackets in Python syntax for that and go checking the indentation if errors happened. Nested if…else is allowed that is using if…else as a response statement while a particular condition_expression is true. In order to judge the logical conditions from mathematics, Python uses the following symbols:

  • Equals: a==b
  • Not equals: a!=b
  • Less than or equal to: a<=b
  • Less than: a<b
  • Greater than or equal to: a>=b
  • great than: a>b

Some logical operators can let you make a complex condition_expression by combining saveral simple ones:

  • and : expression1 and expression2
  • or : expression1 or expression2
math=4<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
english=3

if english &gt;extra English class

# Any subject less than 4 should have extra class
#option 1
if english extra class

#option 2
if englishextra class    

print('extra class') if englishextra class

for and while Loop

for Loop

The for loop is applied for iterating over an iterable object or traversal like we usually do in C/C++. The basic syntax is:

    for val in sequence:
        content of this loop
    else:
        statement fro else part

First of all, else part is just optional and rarely used.
sequence can be an iterable object such as list or string, or a range() function. You can generate numbers from 0 to 9 by using range(10) or range(0,10,1) (start=0, end by=10, step size=1)

<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
# The following three loops come out the same result: print numbers from 0 to 9
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

sequentially
re=[]
for i in range(10):
re.append(i)
print(re)

re.clear()
for i in range(0,10,1):
re.append(i)
print(re)

a=list(range(10))
print(a)

re.clear()
for i in a:
re.append(i)
print(re)

while Loop

The while loop is applied for iterating over a section of code until the testing condition is satisfied (being True). For those cases that you don’t know an exact number of iterations for the repeating jobs, while loop might be a good choice. The basic syntax is:

    while testing_condition:
        statement(S) for while loop
    else:
        statement for else part

The condition will be checked first, and any non-zero value would be considered as True; also, None and 0 are interpreted as False. Same as for loop, the else part is optional and only execute once while the testing condition is False.

#This will result [1, 2, 3, 4, 5, 6, 7, 8, 9]
re=[]
n=10;i=1

while i<n:
    re.append(i)
    i=i+1 #(can also be expressed by i+=1)
print(re)

break, continue, and pass

Break can apllied for both for and while loop, you just put it in the statement (often found with if statement) and it will redirect your program to the outisde of the loop. In contrast to breakcontiune will keep your program to stay in the loop. Finally, if you are looking for a statement which is going to do nothing, using pass.

# the output would be:
'''
i has been 3
i becomes 6  now, let's take a break!
[0, 1, 2, 3, 4, 5, 6]
'''
re=[]
for i in range(10):
    re.append(i)
    if i==6:
        print("i becomes",i," now, let's take a break!")
        break
    elif i==3:
        print('i has been 3')
        pass
    else:
        continue

print(re)

Iterating through tuple, list, string, and dictionary

enumerate() is a very useful function we have to introduce in this part. It returns an enumerate object. It contains the index and value of all the items as a tuple.

S='abcd'
T=('a','b','c','d')
L=['a','b','c','d']
D=dict(zip(range(4),L))   

# the following example adopts for sring, list, and tuple
# all the outputs are all the same

res=[]
#Case 1
for i in S:
    res.append(i)
print('Result of Case 1: ', res)
res.clear()
#Case 2
for i in enumerate(S):
    res.append(i)
print('Result of Case 2: ', res)
res.clear()

# for dictionary
#Case 4
for i in D:
    res.append((i,D[i]))
print('Result of Case 4: ',res)
res.clear()

#Case 5
for i in enumerate(D): #be carefull! enumerate() will pair keys and index
    res.append(i)
print('Result of Case 5: ',res)
res.clear()

#Case 6
for i in D.items():
    res.append(i)
print('Result of Case 6: ',res)

'''
Result of Case 1:  ['a', 'b', 'c', 'd']
Result of Case 2:  [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Result of Case 4:  [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Result of Case 5:  [(0, 0), (1, 1), (2, 2), (3, 3)]
Result of Case 6:  [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
'''

One Comment Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s