Control Structures

A control statement is a statement that determines the control flow of a set of instructions.

Sequence control is an implicit form of control in which instructions are executed in the order that they are written.

Selection control is provided by a control statement that selectively executes instructions.

Iterative control is provided by an iterative control statement that repeatedly executes instructions.

Boolean Expressions

  • Boolean is a specific data type consists of True and False in Python.
  • Boolean expression is an expression that evaluates to a Boolean value.

One way of producing Boolean values is by comparing

  • Relational expressions are a type of Boolean expression, since they evaluate to a Boolean result.


In [1]:
num = 10 # Assignment Operator
num == 12 # Comparison operator


Out[1]:
False

We know that we can compare number for sure, but Python also let's us compare String values based on their character encoding.


In [2]:
10 == 20


Out[2]:
False

In [3]:
print(type('2'))
print('2' < '9')


<class 'str'>
True

In [14]:
if "Aliya" > "Alican":
    print("Aliya is the best!")
else:
    print("No, Aliya is not the best!")


Aliya is the best!

In [18]:
'Hello' == "hello"


Out[18]:
False

In [19]:
'Hello' > 'Zebra'


Out[19]:
False

Another way to get Boolean values is by checking if the membership of given value is valid or not:


In [20]:
'Dr.' in 'Dr. Madison'


Out[20]:
True

In [21]:
10 not in (10, 20, 30)


Out[21]:
False

Boolean (logical) operators , denoted by and, or, and not in Python. It is basically logic,


In [22]:
p = False
r = True

In [23]:
p and r


Out[23]:
False

In [24]:
p or r


Out[24]:
True

In [25]:
not (r and (not p))


Out[25]:
False

The boolean operators will give us a more complex comparison statements which eventually will lead us to better control structures.


In [27]:
num = 15

In [29]:
(1 <= num <= 10)


Out[29]:
False

In [30]:
# Above is equals to 
1 <= num and num <= 10


Out[30]:
False

In [31]:
(10 < 0) and (10 > 2)


Out[31]:
False

In [32]:
not(True) and False


Out[32]:
False

In [33]:
not(True and False)


Out[33]:
True

In [42]:
name = 'Ann'
name in ('Thomas', 'MaryAnn', 'Thomas')


Out[42]:
False

In [43]:
type(('MarryAnn'))


Out[43]:
str

Selection Control

A selection control statement is a control statement providing selective execution of instructions.

An if statement is a selection control statement based on the value of a given Boolean expression.

Syntax:

if condition:
    statements
else:
    statements

You don't have to include else part.


In [46]:
if 10 < 0:
    print("Yes")

In [47]:
grade = 66
if grade >= 70:
    print('Passing Grade')
else:
    print('Failing Grade')


Failing Grade

In [48]:
grade = 100
if grade == 100:
    print('Perfect Score!')


Perfect Score!

Apply it!

Write a small program that converts Fahrenheit to Celcius or vice-verse by getting input from user (F/C)

Indentation is really important in Python since it does not use {} or ;

Multiway selection is possible by nested if else statements:


In [26]:
credits = 45
if credits >= 90:
    print('Senior')
else:
    if credits >= 60:
        print('Junior')
    else:
        if credits >= 30:
            print('Sophomore')
        else:
            if credits >= 1:
                print('Freshman')
            else:
                print('* No Earned Credits *')


Sophomore

However there is a better way to do this using an additional keyword: elif


In [31]:
credits = 45
if credits >= 90:
    print('Senior')
elif credits >= 60:
    print('Junior')
elif credits >= 30:
    print('Sophomore')
elif credits >= 1:
    print('Freshman')
else:
    print('* No Earned Credits *')


Sophomore

Apply It!

Write a small program that prints the day of the specific month of a year. The output will look like this:

Test 1:

This program will determine the number of days in a given month

Enter the month (1-12): 14
*Invalid Value Entered -14*


Test 2:

This program will determine the number of days in a given month

Enter the month (1-12): 2
Please enter the year (e.g., 2010): 2000
There are 29 days in the month

Use if and elif statements

Hint1:

The days of the month are fixed regardless of the year, except February.
Check for 2.

Hint2:

If the year is divisible by 4 but is also divisible by 100, then it is not a leap year— unless, it is also divisible by 400, then it is.

Hint3:

(year % 4 == 0) and (not (year % 100 == 0) or (year % 400 == 0))

Iterative Control

An iterative control statement is a control statement providing the repeated execution of a set of instructions.

Because of the repeated execution, iterative control structures are commonly referred to as “loops” and that's how I am going to name them :)

A while statement is an iterative control statement that repeatedly executes a set of statements based on a provided Boolean expression (condition).

Syntax:

while condition:
    statement

In [2]:
# Initial variables
total = 0
i = 1
n = int(input('Enter value: '))


Enter value: 25

In [3]:
while i <= n:
    total += i # total = total + i
    i += 1
print(total)


325

As long as the condition of a while statement is true, the statements within the loop are (re)executed.


In [8]:
import time
n = 10
tot = 0
i = 1
while i <= n:
    tot = tot + i 
    i = i + 1
    print(tot)
    time.sleep(2)


1
3
6
10
15
21
28
36
45
55

In [9]:
n = 100
tot = 0
while True:
    tot = tot + n
    n = n - 1
    if n == 0:
        break
print(tot)


5050

An infinite loop is an iterative control structure that never terminates (or eventually terminates with a system error). Usually programming errors

let's inspect the following snippet:

# add up first n integers
tot = 0
current = 1
n =  int(input('Enter value: ')
while current <= n:
    tot = tot + current

If your program got stuck in infinite loop you can use special keyboard interruption such as ctrl+C-

Apply It!

Write a small program that displays a random value between 1 and 99 cents, and ask user to enter a set of coins that sums exactly to the amount shown.You should use while loop, if statement, Boolean Flag, random number generator The output will look like this:

The purpose of this exercise is to enter a number of coin values that add up to a displayed target value. 

Enter coins values as 1-penny, 5-nickel, 10-dime, and 25-quarter.
Hit return/enter after the last entered coin value. 
------------------
Enter coins that add up to 63 cents, one per line. 

Enter first coin: 25
Enter next coin: 25
Enter next coin: 10
Enter next coin: 
Sorry - you only entered 60 cents.

Try again (y/n)?: y  
Enter coins that add up to 21 cents, one per line. 

Enter first coin: 11
Invalid entry
Enter next coin: 10
Enter next coin: 10
Enter next coin: 5
Sorry - total amount exceeds 21 cents.

Try again (y/n)?: y
Enter coins that add up to 83 cents, one per line. 

Enter first coin: 25
Enter next coin: 25
Enter next coin: 25
Enter next coin: 5
Enter next coin: 1
Enter next coin: 1
Enter next coin: 1
Enter next coin:
Correct!

Try again (y/n)?: n
Thanks for playing ... goodbye

In [ ]: