0% found this document useful (0 votes)
30 views32 pages

2 Python2 Conditionals

The document provides an overview of decision structures in programming, highlighting the importance of conditional execution to solve problems that cannot be addressed through sequential steps. It covers various types of decision structures, including one-way, two-way, nested, and chained conditionals, along with their syntax in pseudocode and Python. Additionally, it discusses the use of try/except blocks for error handling in code.

Uploaded by

bayansameer2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views32 pages

2 Python2 Conditionals

The document provides an overview of decision structures in programming, highlighting the importance of conditional execution to solve problems that cannot be addressed through sequential steps. It covers various types of decision structures, including one-way, two-way, nested, and chained conditionals, along with their syntax in pseudocode and Python. Additionally, it discusses the use of try/except blocks for error handling in code.

Uploaded by

bayansameer2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Conditional Execution

Introduction to Decision Structures

Some problems simply cannot be solved by


performing a set of ordered steps, one after
the other.
A decision structure (or selection structure)
allows a program to perform actions only
under certain conditions

1-2
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
Different types of decisions

• One way decision

• Two Way Decisions

• Nested Decisions

• Chained Conditionals

1-3
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
Recall: one way decision
Decision Structures in Pseudo code and flowchart
The if statement
– An action only occurs if the decision is true
If condition Then
Statement
Statement
End If
– A diamond symbol is used in flowcharts

Figure 4-1 A simple decision


structure for an everyday task

1-4
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
IF-statement Syntax in python

Pseudocode Python

if expression:
statement(s)
Note the indent

Copyright © 2016 Pearson Education, Inc., Hoboken NJ


Conditional Steps
Yes

Program:

x=5
Yes if x < 10:
print 'Smaller‘
if x > 20:
print 'Bigger'
print 'Finish'
Excercise x=5
if x < 10:
print ('Smaller')

Write a python script that determine the minimum of three values


manually. The script should prompt for and input three values, uses
if statements to determine the minimum value, then displays it.
Comparison Operators
• Boolean expressions = an
expression that evaluates to
true or false < Less than
<= Less than or Equal
• Boolean expressions use == Equal to
comparison operators
evaluate to - True or False >= Greater than or Equal
> Greater than
• Comparison operators look != Not equal
at variables but do not
change the variables Remember: “=” is used for assignment.
x=5
Comparison
if x == 5 :
print ('Equals 5') Operators
if x > 4 :
print ('Greater than 4')

if x >= 5 :
print ('Greater than or Equal 5')

if x < 6 :
print ('Less than 6')
IF with multiple
Yes
Statement
x=5 No

if x == 5 :
print 'Is 5‘
print 'Is Still 5'
print 'Third 5’
Indentation
• Increase indent indent after an if statement or for statement (after : )

• Maintain indent to indicate the scope of the block (which lines are affected
by the if/for)

• Reduce indent back to the level of the if statement or for statement to


indicate the end of the block

• Blank lines are ignored - they do not affect indentation

• Comments on a line by themselves are ignored with regard to indentation


increase / maintain after if
decrease to indicate end of block
blank lines and comment lines ignored
x=5
if x > 2 :
# comments
x=5
if x > 2 :
print 'Bigger than 2'
print 'Bigger than 2'
# don’t matter
print 'Still bigger'
print 'Still bigger'
print 'Done with 2'
# but can confuse you

print 'Done with 2'


# if you don’t line
# them up
Excercise
Read two integers from the user and compare them using six
consecutive if statements, one for each comparison operator. If
the condition in a given if statement is True, the corresponding
print statement executes; otherwise, it’s skipped.
Two Way
Decisions
• Sometimes we want to
no yes
do one thing if a logical
expression is true and
something else if the
expression is false

• It is like a fork in the


road - we must choose
one or the other path
but not both
Two Way
Decisions
Two-way branch
using else :
x=4 no yes

if x > 2 :
print 'Bigger'
else :
print 'Smaller'

print 'All done'


Excercise

Write a python script that prompts for and input a student course
grade. Use if-else statements to determine if the student pass or
fail in the course. (passing grade is >=60).
yes
Nested
Decisions no

x = 42
yes
if x > 1 :
print 'More than one'
no
if x < 100 :
print 'Less than 100'

print 'All done'


Exercise
Assume that the follwoing conditions are
required for a person to be able to get a loan:
- first the Salary>1500
- In his job for at least 12 months. If the salary
condition is qualified then print the remaining
number of months to get the loan.
Write a program that displays if a person is qualified
for a loan or not. Show the reason in case he is not
qualified,
Chained
Conditionals yes

if x < 2 :
no
print 'Small'
elif x < 10 : yes

print 'Medium' no
else :
print 'LARGE'
print 'All done'
Exercise

Suppose we wanted to create a grade conversion program for school.


The user enters a percentage grade, and we want to convert it into a letter grade,
and display that result to the screen. The letter grade is calculated as follows:

1. If the percent grade is between 80 and 100, the letter is A.


2. If the percent grade is between 70 and 79, the letter is B.
3. If the percent grade is between 60 and 70, the letter is a C.
4. Anything below 60 is a D.
Chained if x < 2 :
Conditional print 'Small'
elif x < 10 :
# No Else print 'Medium'
x=5 elif x < 20 :
if x < 2 : print 'Big'
print 'Small' elif x< 40 :
elif x < 10 : print 'Large'
print 'Medium' elif x < 100:
print 'Huge'
print 'All done' else :
print 'Really Huge'
Multi-way Puzzles
Which will never print? if x < 2 :
print 'Below 2'
if x < 2 : elif x < 20 :
print 'Below 2' print 'Below 20'
elif x >= 2 : elif x < 10 :
print 'Two or more' print 'Below 10'
else : else :
print 'Something else' print 'Something else'
The try / except Structure
• You surround a dangerous section of code with try and except.

• If the code in the try works - the except is skipped

• If the code in the try fails - it jumps to the except section

In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the
program gracefully.
astr = 'Hello Bob‘ $ python notry.py Traceback (most
istr = int(astr) recent call last): File "notry.py", line 2,
print 'First‘ in <module> istr =
istrastr = '123‘ int(astr)ValueError: invalid literal for
istr = int(astr) int() with base 10: 'Hello Bob'
print 'Second', istr
astr = 'Hello Bob'
try: When the first conversion fails - it
just drops into the except: clause and
istr = int(astr) the program continues.
except:
istr = -1
Output:
print 'First', istr
First -1
Second 123
astr = '123'
try:
istr = int(astr) When the second conversion
except: succeeds - it just skips the except:
istr = -1 clause and the program continues.

print 'Second', istr


try / except
astr = 'Bob'
try:
print 'Hello'
istr = int(astr)
print 'There'
except:
istr = -1

print 'Done', istr Safety net


Sample try / except
rawstr = input('Enter a number:')

try:
ival = int(rawstr)
Enter a number:42
except:
Nice work
ival = -1
Enter a number:fourtytwo
if ival > 0 :
Not a number
print 'Nice work’
else:
print 'Not a number’
Exercise

Write a script that takes an input from the user and


use the try/except structure to determine if the input
is string or integer
Exercise

Write a pay computation program that gives the


employee 1.5 times the hourly rate for hours worked
above 40 hours (and regular 1.0 rate for less than 40
hours)

Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Exercise
Rewrite your pay program using try and except so
that your program handles non-numeric input
gracefully.

Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input

Enter Hours: forty


Error, please enter numeric input
Summary
• Comparison operators == <= >= > < !=
• Logical operators: and or not
• Indentation
• One Way Decisions
• Two way Decisions if : and else :
• Nested Decisions and Multiway decisions using elif
• Try / Except to compensate for errors

You might also like