You are on page 1of 40

Session 3

Chapter 3

Tamer Elsayed
CSE Dept.
 Set of statements that execute in the order they appear.
stmt1
stmt2
...
stmtn

 All previous programs were in that sequence structure.

CMPS 151 Programming Concepts 2


Assume we want to a grade
and display “Fail” if grade < 60,
and display “Pass” if grade >= 60

Using Decision Structure!

CMPS 151 Programming Concepts 3


 Specific action(s) or statements performed/executed
only if a condition is satisfied.

 To form a condition, we need to use relational


operators.

CMPS 151 Programming Concepts 4


CMPS 151 Programming Concepts 5
 Relational operators are used to compare elements
(numbers or chars) to determine relative order.
 These operators are:

> greater than


< less than
>= greater than or equal to
<= less than or equal to
== equal to
!= not equal to

CMPS 151 Programming Concepts 6


 Relational expressions (called also logical expressions)
have Boolean values, i.e., are either true or false.
 Examples:
12 > 5 true
7 <= 5 false
if x is 10 and y is 7, then
x == 10 true
x != y true
x == 8 false
x < y + 1 false

Do not confuse = (assignment) and == (equal to)


CMPS 151 Programming Concepts 7
CMPS 151 Programming Concepts 8
 The if statement is a control structure: it allows to
control the execution of the program by allowing
statements to be conditionally executed or skipped over.

 It models the way we mentally evaluate situations


“If it is cold outside,
wear a coat and wear a hat.”

CMPS 151 Programming Concepts 9


condition
no
yes

If condition is true, If condition is false,


then the statement(s) 1 or more then the statement(s)
in the body are executed. statements are skipped.

Continue afterwards

CMPS 151 Programming Concepts 10


Example:
Is it cold
outside?

yes

Wear a coat no

Wear a hat

Wear gloves

CMPS 151 Programming Concepts 11


Example:
no
if
Grade ≥ 60

yes
Print “Passed”

Print
“Congratulations”

Print “You grade


is ”, Grade

CMPS 151 Programming Concepts 12


Boolean expression
if condition: if score >= 60:
statement1 print("Passed")
statement2
… body
statementn

if score >= 90:


grade = 'A'
print("Wonderful!")

CMPS 151 Programming Concepts 13


 Do not forget to place : after condition
 Increase indentation after an if statement, to indicate
the scope of the block (which lines are affected by the
if).

 Reduce indentation back to the level of the if


statement to indicate the end of the block.

CMPS 151 Programming Concepts 14


CMPS 151 Programming Concepts 15
condition
no yes

Block2 Block1

If condition is false, If condition is true,


then the block2 is executed then the block1 is executed
and block1 is skipped. and block2 is skipped.

CMPS 151 Programming Concepts 16


 Allows a choice between statements depending on
whether (condition) is true or false

if condition:
Block1 # block of statements
else:
Block2 # block of statements

if clause and else clause must be aligned

CMPS 151 Programming Concepts 17


if score >= 60:
print("Passed")
else:
print("Failed")

if balance >= pay_amount:


balance = balance – pay_amount;
print("New balance is: ", balance)
else:
print("Not enough money.")

CMPS 151 Programming Concepts 18


Write a program to read a number and display if it is
odd or even.

Write a program to read a salary of employee and


deduct 10% tax if the salary is less than 10,000, and
15% if the salary is 10,000 or more. Your program
should display the net salary.

CMPS 151 Programming Concepts 19


What is the output if user enters zero?!

x = int(input('Enter a number: '))


if x > 0:
print('positive')
else:
print('negative')

CMPS 151 Programming Concepts 20


Write a program to read two integer numbers and
display the maximum one.

CMPS 151 Programming Concepts 21


CMPS 151 Programming Concepts 22
 if/else works when we have only 2 choices, but there
are many cases when we have more than 2 choices.
 For example, we want to read a number from user and
decide if it is zero, positive, or negative.

CMPS 151 Programming Concepts 23


x = int(input('Enter a number '))
if x== 0:
print("Zero")
else:
if x > 0:
print('positive')
else:
print('negative')

CMPS 151 Programming Concepts 24


Write a program to read a score, and print the
corresponding letter grade in QU

CMPS 151 Programming Concepts 25


score = int(input('Enter your test score: '))
# Determine the letter grade
if score >= 90:
print('Your grade is A.')
else:
if score >= 80:
print('Your grade is B.')
else:
if score >= 70:
print('Your grade is C.')
else:
if score >= 60:
print('Your grade is D.')
else:
print('Your grade is F.')
CMPS 151 Programming Concepts 26
CMPS 151 Programming Concepts 27
condition1 yes
no

no yes
condition2 Block1

no condition3 yes Block2

no Block3
condition4
yes

Block5 Block4

CMPS 151 Programming Concepts 28


 Special version of a decision structure that makes
logic of nested decision structures simpler to write.
if condition1:
block1
elif condition2:
block2
elif condition3:
block3
elif condition4:
block4
else:
Insert as many elif
block5
clauses as necessary
CMPS 151 Programming Concepts 29
score = float('Enter your final score: '))
if score >= 90:
print('Your grade is A.')
elif score >= 80:
print('Your grade is B.')
elif score >= 70:
print('Your grade is C.')
elif score >= 60:
print('Your grade is D.')
else:
print('Your grade is F.')

CMPS 151 Programming Concepts 30


CMPS 151 Programming Concepts 31
 Used to create relational expressions from other
relational expressions.

Operator Explanation
and relational expression is true if both 0,0=0
0,1=0

expressions are true 1,1=1

or relational expression is true if either


expression is true
0,0=0
0,1=1
1,1=1

not Reverses the value of an expression; true


expression becomes false, false 0=1
expression becomes true 1=0

CMPS 151 Programming Concepts 32


 x = 12, y = 5, z = -4

(x > y) and (y > z) true and true=true true

(x > y) and (z > y) true and false=false false


(x <= z) or (y == z) false or false=flase false
(x <= z) or (y != z) false or true=true true
not (x >= z) true=flase false

CMPS 151 Programming Concepts 33


Precedence Operator
Highest not
and
Lowest or
Example:
true False
(2 < 3) or (5 > 6) and (7 > 8)
true or false=true flase and false=flase

is true because AND is evaluated before OR

CMPS 151 Programming Concepts 34


Precedence Operator
Highest arithmetic operators
(e.g. +, -, *, /)
relational operators
(e.g. >,<,<=,>=,==)
Lowest logical operators (and, or, not)

Example:
8<9 or 5==6 8 < 2 + 7 or 5 == 6 true
true or false
true
evaluated evaluated evaluated evaluated
2nd 1st 4th 3rd

CMPS 151 Programming Concepts 35


Operator Name Associativity Operators

Primary left to right ()

Unary right to left + - not

Exponentiation left to right **

Multiplicative left to right * / // %

Additive left to right + -

Relational left to right < > <= >=

Equality left to right == !=

Logical AND left to right and

Logical OR left to right or


CMPS 151 Programming Concepts 36
 Used to test if a value is within a range
if grade >= 0 and grade <= 100:
print("Valid grade“)
 Can also test if a value lies outside a range
if grade < 0 or grade > 100:
print("Invalid grade")

 Cannot use mathematical notation


if 0 <= grade <= 100: # doesn’t work!

if 0 <= grade and grade <= 100: # works!

CMPS 151 Programming Concepts 37


 Input validation: inspecting input data to determine if it
is acceptable, to avoid accepting bad input.
 Can perform various tests. Examples:
● Range
● Valid menu choice
● Zero as a divisor

CMPS 151 Programming Concepts 38


Write a program to read three integer numbers and
print the maximum.

CMPS 151 Programming Concepts 39


A software company sells a package that retails
for $99. Quantity discounts are given according to
the following table:

if q >=20 and q<49:


s=q*99
t=s*.2
cost=s-t
print(cost)
Write a program that asks the user to enter the
number of packages purchased. The program
then displays the amount of the discount (if any)
and the total cost after the discount.
CMPS 151 Programming Concepts 40

You might also like