Topic 4 - Python-Conditional Execution 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 39

Imam Abdulrahman Bin Faisal University

Deanship of Preparatory Year and Supporting Studies

Basics of Programming through Python


Conditional Statements

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

A Structured programming is an important feature of a


programming language which comprises following logical
structure:

1. SEQUENCE
2. SELECTION
3. ITERATION OR LOOPING
4
Selection Structure

A selection statement causes the


program control to be transferred
to a specific flow based upon
whether a certain condition is
true or not.

5
Introduction to conditional statements

 Conditional statements are used to control the flow of


the program.
 Conditional statements in Python perform different
computations or actions depending on whether a
specific Boolean constraint evaluates to true or false.
 if, elif, and else are the conditional statements in
Python.
6
Conditional Exécution: if statement

▪ Conditional statements check conditions and change the behavior of the


program accordingly.
▪ The simplest form is the if statement: (one selection statement)

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

 There are a few important items to remember about if


statements:
 The colon (:) is important and essential.
 The header of the compound statement (i.e. if
statement) is isolated from the body.
 All rows indented after the colon will be executed
whenever the Boolean expression is valid.
10
Python Blocks
▪ Python uses indentation for blocks and nested
blocks.
▪ Code Blocks
▫ A code block is a set of statements that will be
executed together, one after the other
▫ If statements, for loops, while loops, functions, are
all code blocks
▫ Example:

11
if---else: Example 1

12
if---else: Example 2

▪ Find the output of this code?


A=15
B=20
If B>A:
print(“B is greater than A”) B is greater than A
Else:
print(“A is greater than B”)

13
if …. elif Statement

 The elif keyword is python way of saying :”if the


previous conditions were not true, then try this
condition.
 elif is abbreviation of else if.
 There is no limit of the number of elif statement.
but only a single final else is allowed and it must
be the last branch in the 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:

Output: Junior Discount

16
If—elif: Example 2

Find the output of this code:

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

 There are three logical operators: and, or, and not.

 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) istrue 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:

inp = input('Enter Fahrenheit Temperature: ')


fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)

 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

▪ After the except clause(s), you can


include an else-clause. The code in
the else-block executes if the code in
the try: block does not raise an
exception.
▪ The else-block is a good place for
code that does not need the try:
block's protection.

30
Try and check

Find the output if:


▪ Var 1=6 and Var 2=3
▪ Var 1=6 and Var 2=12
▪ Var 1=6 and Var 2=0
▪ Var 1=0 and Var 2=2

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

Find the output when:


▪ name=Ahmed
▪ name=Emy
▪ name=Lee
▪ name=Zaineb

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

y=0, which causes a The first part of these expressions


runtime error x >= 2 evaluated to False so the
(division by zero) (x/y) was not ever executed.
(short-circuit) 34
Short-circuit evaluation of logical expressions
 A guard evaluation can be strategically placed before the evaluation that might
cause an error.

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

 Error (without guard evaluation) 35


Try and check 1

Rewrite your pay computation to give the employee


1.5 times the hourly rate for hours worked above 40
hours.

• 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

You might also like