Topic 4 - Python-Conditional Execution 2
Topic 4 - Python-Conditional Execution 2
Topic 4 - Python-Conditional Execution 2
Introduction to programming
COMP102
Term 3 | 2022-2023
Python Conditional
Statements
Learning outcomes
Understand the concept and usage of selection structure
and conditional statements.
Know various types of conditional statements available in
Python (if, elif, Nested if).
Handling an exception using try, except else and finally.
Analyze the problem, decide, and evaluate conditions.
3
Types of control structures
1. SEQUENCE
2. SELECTION
3. ITERATION OR LOOPING
4
Selection Structure
5
Introduction to conditional statements
if
if x > 0 :
print('x is positive')
If Logic 7
if--else statement
An “if statement” is written by using the if keyword.
Python if statement is used for decision-making operations.
It contains a body of code which runs only when the condition
given in the if statement is True. If the condition is False, then the
optional else statement runs which contains some code for the else
condition.
Syntax of iF-else statement:
if condition:
statement_1_True
else: 8
statement_false
Alternative Execution: if-else
▪ There are two possibilities and the condition determines which one gets
executed. (two-way selection statement)
False True
if
if x%2 == 0 :
print('x is even’)
else :
print('x is odd')
If-Then-Else
Logic 9
If---else statements
11
if---else: Example 1
12
if---else: Example 2
13
if …. elif Statement
14
Chained Conditionals
▪ Sometimes, there are more than two possibilities, and we need
more than two branches. (Multiple-Way )
if x < y: if
print('x is less than y')
elif x > y: No
if
print('x is greater than y')
else: No
print('x and y are equal')
If-Then-ElseIf Logic 15
If---elif: Example 1
Find the output of this code:
16
If—elif: Example 2
17
Nested Conditionals
▪ One conditional can also be nested within another:
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y’)
else:
print('x is greater than y')
Nested If Statements 18
Nested If Statement---syntax
19
Nested if…Example
Find the output of the code below.
Rewrite the code using if—elif statement
20
Comparison Operators
Boolean expressions ask a Python Meaning
question and produce a Yes or No < Less than
result which we use to control
<= Less than or Equal to
program flow
== Equal to
>= Greater than or Equal to
Boolean expressions using
> Greater than
comparison operators to evaluate to
True / False or Yes / No != Not equal
is The same as
is not Not the same as
Comparison operators look at
variables but do not change the
variables Remember: “=” is used for assignment.
21
Comparison Operators
x=5
if x == 5 :
print('Equals 5') Equals 5
if x > 4 :
Greater than 4
print('Greater than 4')
if x >= 5 : Greater than or Equals 5
print('Greater than or Equals 5')
Less than 6
if x < 6 : print('Less than 6')
if x <= 5 : Less than or Equals 5
print('Less than or Equals 5')
Not equal 6
if x != 6 :
print('Not equal 6')
22
Logical Operators
x > 0 and x < 10 is true only if x is greater than 0 and less
than 10.
n%2 == 0 or n%3 == 0 is true if either one of the conditions is
true, that is, if the number is divisible by 2
or 3.
not (x > y) istrue if x > y is false; that is, if x is less
than or equal to y.
Any nonzero number is interpreted as “True.”
17 and True True 23
Truth table
24
Python Exceptions Handling
▪ Python provides two very important features to handle any unexpected error
in your Python programs and to add debugging capabilities in them:
▫ Exception Handling
▫ Assertions
What is Exception?
▪ An exception is an event, which occurs during the execution of a program,
that disrupts the normal flow of the program's instructions.
▪ In general, when a Python script encounters a situation that it can't cope with,
it raises an exception. An exception is a Python object that represents an error.
25
Handling an exception
▪ If you have some suspicious code
Syntax:
that may raise an exception, you can
try:
defend your program by placing the
You do your operations
suspicious code in a try: block.
here;
▪ After the try: block, include an ......................
except: statement, followed by a except Exception I:
block of code which handles the If there is Exception, then
problem as elegantly as possible. execute this block.
26
Catching exceptions using try and except
▪ Here is a sample program to convert a Fahrenheit temperature to a Celsius
temperature:
If we execute this code and give it invalid input, it simply fails with an
unfriendly error message
27
Catching exceptions using try and except
If an exception (error) occurs in the
try block, Python jumps out of the try
inp = input('Enter Fahrenheit block and executes the sequence of
Temperature:') statements in the except block.
try:
fahr = float(inp) You can use try & except with any
cel = (fahr - 32.0) * 5.0 / 9.0 script code.
print(cel) You can write try: at a beginning
except: of your code or anywhere else.
print('Please enter a number') You can write any script code in
except not just print.
28
Try and Except: Find the output?
29
try except else
30
Try and check
31
The Try-Finally Clause
▪ You can use a finally: block The syntax of the try-finally
along with a try: block. statement is this:
▪ The finally block is a place to try:
put any code that must execute, You do your operations here;
whether the try-block raised an ......................
exception or not. Due to any exception, this may
be skipped.
▪ Note that you can provide
finally:
except clause(s), or a finally
This would always be
clause, but not both. executed.
.................
32
Try and check
33
Short-circuit evaluation of logical expressions
▪ When the evaluation of a logical expression stops because the overall value
is already known, it is called short-circuiting.
x=6 x=1
y=0 y=0
x >= 2 and (x/y) > 2 x >= 2 and (x/y) > 2
Error False
x=1 x=6
y=0 y=0
x >= 2 and y != 0 and (x/y) > 2 x >= 2 and y != 0 and (x/y) > 2
False False
x=6
y=0
x >= 2 and (x/y) > 2 and y != 0
• Enter Hours: 45
• Enter Rate: 10
• Pay: 475.0
36
Try and check 2
Rewrite your pay program using try and except so that your program
handles non-numeric input gracefully by printing a message and exiting
the program. The following shows two executions of the program:
• Enter Hours: 20
• Enter Rate: nine
• Error, please enter numeric input
• Enter Hours: forty
• Error, please enter numeric input
37
Try and check 3
Write a program to prompt for a score between 0.0 and 1.0. If the score is out of
range, print an error message. If the score is between 0.0 and 1.0, print a grade
using the following table:
Enter score: 0.95
>= 0.9 A A
>= 0.8 B Enter score: perfect
>= 0.7 C Bad score
>= 0.6 D Enter score: 10.0
< 0.6 F Bad score
Enter score: 0.75
Run the program repeatedly as follows to test the C
various different values for input. Enter score: 0.5
F
38
Thanks!
Any questions?
39