0% found this document useful (0 votes)
11 views54 pages

Lesson 3 Decisions and Branching

This lesson introduces decision-making in Python programming using the if statement, explaining its syntax and how to evaluate conditions. It covers additional features such as the else clause, elif statements for multiple conditions, and compound conditions using logical operators. By the end of the lesson, learners will be able to implement decision structures in their programs effectively.

Uploaded by

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

Lesson 3 Decisions and Branching

This lesson introduces decision-making in Python programming using the if statement, explaining its syntax and how to evaluate conditions. It covers additional features such as the else clause, elif statements for multiple conditions, and compound conditions using logical operators. By the end of the lesson, learners will be able to implement decision structures in their programs effectively.

Uploaded by

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

Lesson 2: Decisions, Decisions

Introduction to Python Programming


Lesson 2: Decisions, Decisions

Lesson Overview

Introduction

The if Statement

Additional Features

Compound Conditions

Review
Introduction


So far, you've learned how to do input
and output, as well as some
interesting calculations with numbers
and words.

However the programs haven't taken
advantage of the computer's ability to
choose which set of statements to
execute based on some condition.

3
Introduction


So far, you've learned how to do
input and output, as well as some
interesting calculations with
numbers and words.

However the programs haven't
taken advantage of the
computer's ability to choose
which set of statements to
execute based on some condition.

4
Introduction


Think about a bank ATM. It
allows you to access your account
and withdraw money.

But before you can do so, the
computer needs to check your
account to be sure you have
enough money to cover the
transaction.

Similarly other programs such as
Ethio Telecom’s package purchase
interface employ conditional’s.

5
Introduction


In this lesson you’ll learn all
about making decisions in Python
with the if statement.

You’ll learn its basic syntax and
the different kinds of operators
used to describe conditions.

By the end, you will be able to
write programs that determine
which statements should be
executed as the program runs
based on inputs from your users.

6
The if Statement

7
The if Statement


Python programs can evaluate a condition and
then either perform a set of instructions or not.

It's important to note that the computer can only
handle yes-or-no questions i.e conditions evaluate
to either true or false.

One great thing about the if statement in Python
is that it works pretty much like an if statement in
real life.

That is, you write the code so that if some condition is true, then the
computer executes the lines of code that follow.

8
The if Statement: Syntax


To the right you can see
the basic syntax for the
Python if statement.

The < and > signs
indicate what’s inside
them is to be replaced
with a valid python
statement which is
appropriate.
For the <condition> it

has to evaluate to a
boolean value.
9
The if Statement: Syntax


1) This statement starts
with the keyword if,
followed by some condition.

2) The condition that you
put in your code is known as
a Boolean condition. This
just means that the
condition must evaluate to
either true or false.
If the condition evaluates to true, then
the next statements will be run.
Otherwise, the program will continue with
the statements that aren't part of the if.

10
The if Statement: Syntax


3. Another important part of the
first line is the colon (:) at the
end.

It is necessary because it separates the
condition from the statements to be
performed if the condition is true.

4. The next line of code is where
you'll put the statements that
you want executed if the
condition is true.

In Python, you can list as many statements to
be run here as you want.

The key is that these statements must be
indented.

The indentation has to be consistent.

11
The if Statement: Syntax


5. The final line here is
outside of the if
statement. Such
statements are always
executed, whether the
condition is true or not.

12
The if Statement: Relational Operators

Operation Operator

To write conditions then
you need to know some Less than <
of the operators that are
used for comparison. Less than or equal to <=


The table shows the six
Greater than >
relational operators used
for comparison: Greater than or equal to >=

Equal to ==

Not equal to !=

13
The if Statement: A Numeric Example


Here’s a simple code that
demonstrates what we’ve
seen so far.
age = 10
if age == 10:
print ("ten")

Try changing the operator
in the condition to see how
the code behaves.

14
The if Statement: A Numeric Example


Here’s another example
which uses multiple if
statements.

Try to run it!

15
The if Statement: A String Example


Condition can be used that involve strings.

In Python, comparing strings is done exactly the
same way as comparing numbers.
name = "Abebe"
if name == "Abebe":
print ("the same")

This should make sense, but what about the other
operators? What does it mean for one string to be
less than another?

16
The if Statement: A String Example


Try this in IDLE.

17
The if Statement: Unicode Character
Order


If there is more than one character, then Python just
does the comparison like a dictionary.

The comparison of each character is based on the
value that is used to store it.
Python uses Unicode values for this.


Unicode is a table that correlates numbers to
characters. You may have heard of ASCII, which is a
subset of Unicode. Basically put, ASCII can handle
128 different characters. This works fine for the
English language, but what about other languages?

As a response Unicode was developed.

18
The if Statement: Unicode Character
Order


Here’s the important part: in Unicode, all the
uppercase letters come before any of the
lowercase letters.

Therefore “a”>”A” is True. Same with “b”>”Z” .

Try this code to see for your self.

19
The if Statement: Unicode Character
Order


ASCII table

20
The if Statement: Unicode Character
Order

Some of the UNICODE character with their


numeric values.

home.unicode.org/

21
The if Statement: Unicode Character
Order


Some of the UNICODE
character with their
numeric values.

home.unicode.org/

22
The if Statement: Unicode Character
Order

home.unico

de.org/

23
Additional Features: The else Clause


You just learned how to get the computer to do
something if some condition is true.
This is sometimes called the one-way if statement.


However, what happens if you want the computer
to do one thing if the condition is true and
something different if the condition is false?

To handle such a situation, you can add an else
clause to your code and create a two-way if
statement.

One thing to keep in mind is that you can have an if without an else but
never an else without an if.
25
Additional Features: The else Clause


So the general format of the if else statement is
this:

26
Additional Features: The else Clause


Notice once again that
after the keyword else,
we have a colon (:).

Again, this is to tell the computer
that the next statements are to be
done when the condition is false.

Also notice how once
again the statements
that are part of the else
are indented.

27
Additional Features: The else Clause


Try this code in IDLE.

28
Additional Features: The else Clause


So far we’ve seen codes where the “true
statements’ or ‘false statements’ are on single
line of code.
This is not a rule – it was just simple to

demonstrate the if statement that way.


You can include multiple lines of code in those

blocks.

29
Additional Features: Including More
Than Two Choices


So far our if statement only checked one
condition.

But what if there are more choices.

For example, what if you're writing a program
that prints the term that describes a student's
status during each year of school—freshman,
sophomore, and so on?

Or when you’re buying a package from Ethio
Telecom by dialling *999#
We can use multiple if statement as we did

previously.
30
Additional Features: Including More
Than Two Choices


Here’s how we can do that:-

The program will run – but it’s inefficient.

31
Additional Features: Including More
Than Two Choices


The program will run – but it’s inefficient.

It’s inefficient because – if let’s say the first
condition is true – there is no need to check for
the other conditions which in this case, and in
most case are mutually exclusive.

Doing those comparisons just wastes time. The
nested structure is an easy fix, and you will learn
about it next. With it, you can put an if
statement inside another if statement.

32
Additional Features: Nested if
Statements


The term nesting refers to
the fact that you're putting
one thing inside another.

When you use nested if
state you put another if
statement in the “true
statements” or “false
statements” section.

33
Additional Features: Nested if
Statements


Here’s an example:-

34
Additional Features: Nested if
Statements


Because of the way Python is set up, you have
to be very careful to watch your indenting in
this situation.

Python uses the indenting to determine where
the ifs and elses line up.

If you're using Tabs to indent, this can get a
little worrisome because you'll quickly run out of
space.

For this reason, Python has given us the ability
to use another keyword, elif. You’ll learn about
that next.
35
Additional Features: The elif Statement


As you might guess, elif is just a combination of
the words else and if. So, your earlier program
becomes this:

36
Additional Features: The elif Statement


As you might guess, elif is just a combination of
the words else and if. So, your earlier program
becomes this:

37
Additional Features: The elif Statement


If you compare this code to the previous
example, you'll see that the indenting here is
much easier to read and doesn't take up so
much room.
Many people argue that this makes the code easier to read.


The functionality of the code is exactly the
same as in the previous example.

So, once the computer makes a match between
the value of year and the number, the output
will be displayed and it'll stop comparing values.

38
Additional Features: Revealing Invalid
Entries


Here’s one last advantage of the nested if and
elif statements.

You can add a final else statement that will reveal
invalid entries.

With the code above, notice that if the user
enters a number other than 1, 2, 3, or 4, nothing
is printed.

So, if the user enters a 5 and nothing happens,
the user or (or the programmer) might think there
is a problem with the program, and the
programmer would have to spend time figuring
out what went wrong.
39
Additional Features: Revealing Invalid
Entries


But you can avoid this problem by adding the
following:
else:
print ("Not a valid year")

Now when you run the program and enter something
that isn't between 1 and 4, you'll still get a message.

This is quite helpful for debugging your programs.

Doing multiway if statements makes your programs
easier to write and quicker to run. But what if you
want to check two or more conditions in your if
statement?

40
Compound Conditions: Logic Operators

There are lots of situations where you might want to make


a decision based on more than one condition.


In the earlier voting example, suppose you want a

program that checks that users are at least 18 years old


and registered to vote.
One way to do this would be to put one if statement inside

another like this:

41
Compound Conditions: Logic Operators


This code will ask users for
their age and if they're
registered to vote. It will
even give the correct
response if the user happens
to be old enough and
registered. However, there's
a small problem.

Notice what happens if
you're old enough but not
registered to vote. In this
case, no message is printed
on the screen.

42
Compound Conditions: Logic Operators


Therefore we’ve to include another else for the
nested if statement and out code will look like
this:-

43
Compound Conditions: Logic Operators

This works but if we have a lot of cases this can get a bit

messy and hard to read or easily debug.


Therefore Python offers compound conditions to make

our life easier.


In order to create a compound condition, you need to use

a logic operator.
The most common operators in Python are And and Or.


Compound conditions with the And operator require that both individual conditions
are true in order for the overall compound condition to be true.

Conditions that use an Or operator require that at least one of the individual
conditions be true for the overall condition to be true.

44
Compound Conditions: The And
Operator


In our voting example, we'd want to use the And
operator to require that the user be at least 18
and registered to vote. Here's what the code looks
like now:

45
Compound Conditions: The And
Operator


If you’ve statements of the kind:


Python allows you to write it as:

46
Compound Conditions: The Or Operator


The Or operator works exactly the same. For
example, maybe you want to write an if statement
to test whether your user has entered either "Y" or
"y".

Your statement could look like this:

47
Compound Conditions: More About the
Or Operator


What if you try to write this piece of code:-

This is not a valid syntax in Python –


however Python won’t generate an error


but will just run by interpreting “y” as the
Boolean value true.

48
Compound Conditions: Truth tables


The table displays the truth table for the
various compound conditions.

49
Compound Conditions: A Weekly Pay
Example


Let’s pull what we’ve seen so far to write a
somewhat useful program.
Let's create one that will ask users for their

hourly rate and the number of hours they've


worked.

50
Temprature Converter


Here’s a program that converts between C and F.

51
Currency Converter

Try to write a program that converts between


Birr, Dollar and RMB.


Use this conversion rates: (or the current rates.)

1 USD= 53 Birr
1 RMB= 8 Birr
1 USD = 6.625

52
Even or Odd


Write a program tha prompts the user for two
integers and check if they are multiples of each
other.
Write a program that prompts the user for a

number and check if it’s even or odd.

53
Lesson 2 Review


Python only provides one way to do decisions in
your programs with the if statement.

However, as you've seen, even with only one
decision structure, there are a lot of ways you can
arrange your code.
There are else clauses and elif statements.

You also learned about the logic operators and


how they create compound conditions.


In the next lesson we will see loops.

54
Some exercises:


Write a program that converts between C, F
and K. Prompt the user for what they want to
convert and display the temperature in the
other two.

Write the quadratic solver using the math
library. His time the program should display
“Two solution : solution 1 and solution 2” , “One
solution: solution 1” or “No solution” depending
on the coeficients.

55

You might also like