CH 6
CH 6
CH 6
CONTROL -6
(SELECTION)
Basimah Aljhne
Decision Structure
• 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
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
• 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
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
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.
Positive
Positivenumber
number Zero
Zeronumber
number
Convert the following diagram into python code.
False True
pH > 7
True True
pH is 7 pH < 12
True ‘Very
pH > 2 alkaline’
False ‘Acidic’
‘Very
acidic’
Control in Depth : Boolean Click icon to add picture
Boolean Variables
• Boolean value True is stored as 1
•The result of evaluating something like the above is also just true or false.
2 > 3True
2 – 3 < 3 + 5
False
2 < '1Error
'
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
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