You are on page 1of 52

Click icon to add picture

CONTROL -6
(SELECTION)
Basimah Aljhne
Decision Structure

The sequence structure


Click icon to add picture

1. The Selection Statement for Decisions


2. Control in Depth : Boolean
The Selection Statement for Decisions
Click icon to add picture
1. Selection
2. Boolean for Decision
3. if statement
4. Indentation and Suite of Python code
5. If else statement
6. If-elif-else Statements
7. Nested if Statements
Selection

• Up to this point, all we have been able to do is write Python code that is executed
sequentially—that is, one statement after another
Selection

• In programming, selection is the process of applying a


decision to control: the choice of executing one part of a
program or another.

Is an expression that is true or


false
“condition”

After evaluation the selection boolean_expression


(T or F) a Boolean result is returned to be used in
The selection .

Either way, after having finished with the selection


We continue on the rest of the program
Boolean for Decision

• A Boolean type can take on only one of two


values: True or False .
• A Boolean can be used as a condition as
discussed.
• In a selection statement, if a condition
expression evaluates to True , then selection
will evaluate one part of the program; if the
expression is False , selection will execute a
different part of the program.
• Both selection and repetition require a
condition expression that evaluates to True or
Note that == is equality,
False as part of their control.
= is assignment
if statement
The Basic if Statement

if boolean expression : Suite: is a set of statements


#if suite That has the same indentation.

1. evaluate the boolean (True or False)


2. If boolean_expression True
a) Execute the python suits of code indented under the if (if suits)
b)Once the indented code is executed, continue with any python code after the
indented code.

3. If boolean_expression False
a) Ignore the code indented the if
b)continue with any python code after the indented code.
1.52

35

15.15
1.52

52

22.51
Indentation and a Suite of Python Code

 Indentation in Python matters.


 Indentation is Python’s method for associating or grouping statements.
 Indentation gets used in many Python statements, including the if statement.
 For if ,the indentation indicates that the indented statements following the if are
associated with that if .
 This group is called a compound statement, where the if keyword is part of the
header and the set of indented statements is called the suite
 A compound statement is considered to be one logical statement.
Indentation and a Suite of Python Code

Compound statements involve a set of statements being used as a group


 Most compound statements have:
 a header, ending with a : (colon)
 a suite of statements to be executed
 if, for, while are examples of compound statements
Indentation and a Suite of Python Code

• Elements of the suite must all be indented the same number of spaces/tabs
• Python only recognizes suites when they are indented the same distance
(standard is 4 spaces)
• You must be careful to get the indentation right to get suites right.
:Write this code
Fix the error

Using wrong boolean


Operators
If else statement

• The if else statement operation is as follows:


• Evaluate boolean expression to yield True or False .
• If boolean expression yields True ,
Execute the if suite, indented under the if .
Continue with the rest of the Python program.

• If boolean expression yields False


Execute the else suite, indented under the else
Continue with the rest of the Python program.
If else statement

example: Write program that take 2 number from the user then print the bigger
number?
Write the code
Which of these fragments are valid and invalid first lines of if statements? Explain why:
if (x > 4) valid
if x == 2 valid
if (y =< 4) invalid (Y<=4)
if (y = 5) invalid (Y==5)
if (3 <= a) valid Check yourself
if (1 - 1) valid
boolean Operators
if ((1 - 1) <= 0) valid
if (name == "James") valid

if (1 - 1)

if (0)
What is the output of the following code? Explain why.

if (5
(1 - 1):

Note that:
True=any non zero value
False=0
Do it home

Example 1: Program checks if the number is positive or negative


# And displays an appropriate message

Example 2: Write a Python program to convert temperatures to and from celsius,


fahrenheit.
[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in
fahrenheit ]
Expected Output :
60°C is 140 in Fahrenheit
45°F is 7 in Celsius
If-elif-else Statements
1- Evaluate Boolean expression1 to
if boolean expression1: Yield True or False
suite1
2-If boolean expression1 yields True,
A. Execute suite1
elif boolean expression2: B. Continue with the next statements after suite_last
suite2
3-If boolean expression1 yields False, then evaluate boolean
(as many elif's as you expression2
want) If it return True
A. Execute suite2
else: B. Continue with the next statements after suite_last
suite_last
4-If all preceding boolean expression yiled False
A. Execute else part and suite_last
B. Continue with the next statements after suite_last
If-elif-else Statements
•Write a program that will ask the user to enter a grade, then print out the Grade
symbol according to the following grading scale:

Grade Grading Scale


G >=90 A
G >= 80 => 89 B
G >= 70 => 79 C
G >= 60 => 69 D
G < 60 F
40 Run!

Grade Grading Scale


G >=90 A
G >= 80 => 89 B
G >= 70 => 79 C
G >= 60 => 69 D
G < 60 F

last memory:
grade

F
In an earlier set of exercises, you were asked to calculate
one’s BMI. Augment that program by printing out where
that BMI fits in the CDC standard weight status
categories:
Nested if Statements
• There may be a situation when you want to check for another condition after a
condition resolves to true.
• In such a situation, you can use the nested if construct.

• Any number of these statements can be nested inside one another.


• Indentation is the only way to figure out the level of nesting.
• This can get confusing, so must be avoided if we can.
inner if
false num
num>=
>=00??
true

Nested if false true Nested


Negative
Negative num
num==
==00?? if
number
number

Positive
Positivenumber
number Zero
Zeronumber
number
 Convert the following diagram into python code.

False True
pH > 7

True True
pH is 7 pH < 12

False ‘Neutral’ False ‘Alkaline’

True ‘Very
pH > 2 alkaline’
False ‘Acidic’

‘Very
acidic’
Control in Depth : Boolean Click icon to add picture

1. True and False : boolean


2. Boolean Variables
3. Boolean operators
True and False : boolean
• George Boole's (mid-1800's) mathematics of logical expressions
• Boolean expressions (conditions) have a value of True or False
• Conditions are the basis of choices in a computer, and, hence, are the basis of the
appearance of intelligence in them.
• What is True, and what is False?

Boolean Variables
• Boolean value True is stored as 1

• Boolean value False is stored as 0

True: any nonzero number or nonempty object. 1, 100, "hello", [a,b]


False: a zero number or empty object. 0, "",[ ]
Boolean operators
Every boolean expression has the form:

expression boolean_Operator expression

•The result of evaluating something like the above is also just true or false.

2 > 3True
2 – 3 < 3 + 5
False
2 < '1Error
'

int('1') < 2 True

Relational Operators
?What does Equality mean
•Two different kind of equality:
•Two different name are associated with objects that have the same value
•Two different name are associated with the same object.(objects with same id)
equal vs. same
== compares values of two variable's objects, do they represent the same value
is operator determines if two variables are associated with the same value

From the figure:


a_float == b_float  True
a_float is b_float  False
b_float is c_float  True
Precedence & Associativity
Relational operators have precedence and associativity just like
numerical operators.
Truth Tables
Explain the difference between “is” and “==”. Give an example
that illustrates items that return False for “is” and True for “==”.

== compares values of two variable's objects, do they represent the


same value
is operator determines if two variables are associated with the same value

Fill in the following table with values True or False —one


value in each empty box.
False
True True True True True
False False
False False True False
True True False False
True False False False
Write a Python program to assign grades to students at the end of
the year. The program must do the following:
• Ask for a student number.
• Ask for the student’s tutorial mark.
• Ask for the student’s test mark.
 Calculate student’s tutorial mark +test mark.
 If the summation of the student’s so far is high enough for the
student to be permitted to write the examination.
The Sumiton of their mark should be <=50
If the tutorial and test marks is lower than 50, the student should
automatically get an F grade, and the program should print the
grade and exit without performing the following steps.
• Ask for the student’s examination mark.
 add the student’s final mark to his tutorial and test mark
Calculate and print the student’s grade, according to the following
table:
• Ask for a student number.
• Ask for the student’s tutorial mark.
• Ask for the student’s test mark.

 Calculate student’s tutorial mark +test


mark.
 If the summation of the student’s so far is
high enough for the student to be
permitted to write the examination.
The Sumiton of their mark should be <=50
If the tutorial and test marks is lower than
50, the student should automatically get an F
grade, and the program should print the
grade and exit without performing the
following steps.
• Ask for the student’s examination mark.
 add the student’s final mark to his tutorial and test mark
Calculate and print the student’s grade, according to the following table:
SUMMARY
If/elif/else Selection
Selection If/ else selection

if Selection

if grade >=60:
print(“passed”)
else: if condtion:
if grade >=60: Print(“failed”) #suit
print(“passed”) Elif condtion:
#suit
Else:
#suit
Selection Nested IF Selection

inner if
false num
num>=
>=00??
true

false true
Negative
Negative num
num==
==00??
number
number

Positive
Positivenumber
number Zero
Zeronumber
number
Read

You might also like