0% found this document useful (0 votes)
28 views5 pages

3.2.5 Conditional Execution

The document discusses conditional execution in Python, including if, else, elif statements and nested conditionals. It explains the syntax and flow of conditional statements, and how to write programs that perform different actions depending on certain conditions.

Uploaded by

dimpyrathi23
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)
28 views5 pages

3.2.5 Conditional Execution

The document discusses conditional execution in Python, including if, else, elif statements and nested conditionals. It explains the syntax and flow of conditional statements, and how to write programs that perform different actions depending on certain conditions.

Uploaded by

dimpyrathi23
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/ 5

How to Think Like a Computer Scientist: Learning with Python 3 Documentation, Release 3rd

Edition

not (not x) == x

3.2.5 Conditional execution

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of
the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

1 if x % 2 == 0:
2 print(x, " is even.")
3 print("Did you know that 2 is the only even number that is prime?")
4 else:
5 print(x, " is odd.")
6 print("Did you know that multiplying two odd numbers " +
7 "always gives an odd result?")

The Boolean expression after the if statement is called the condition. If it is true, then all the indented statements get
executed. If not, then all the statements indented under the else clause get executed.

Flowchart of an if statement with an else clause

The syntax for an if statement looks like this:

1 if <BOOLEAN EXPRESSION>:
2 <STATEMENTS_1> # Executed if condition evaluates to True
3 else:
4 <STATEMENTS_2> # Executed if condition evaluates to False

As with the function definition from the next chapter and other compound statements like for, the if statement
consists of a header line and a body. The header line begins with the keyword if followed by a Boolean expression
and ends with a colon (:).
The indented statements that follow are called a block. The first unindented statement marks the end of the block.

34 Chapter 3. Program Flow


How to Think Like a Computer Scientist: Learning with Python 3 Documentation, Release 3rd
Edition

Each of the statements inside the first block of statements are executed in order if the Boolean expression evaluates to
True. The entire first block of statements is skipped if the Boolean expression evaluates to False, and instead all
the statements indented under the else clause are executed.
There is no limit on the number of statements that can appear under the two clauses of an if statement, but there has
to be at least one statement in each block. Occasionally, it is useful to have a section with no statements (usually as
a place keeper, or scaffolding, for code we haven’t written yet). In that case, we can use the pass statement, which
does nothing except act as a placeholder.

1 if True: # This is always True,


2 pass # so this is always executed, but it does nothing
3 else:
4 pass # And this is never executed

3.2.6 Omitting the else clause

Flowchart of an if statement with no else clause

Another form of the if statement is one in which the else clause is omitted entirely. In this case, when the condition
evaluates to True, the statements are executed, otherwise the flow of execution continues to the statement after the
if.

1 if x < 0:
2 print("The negative number ", x, " is not valid here.")
3 x = 42
4 print("I've decided to use the number 42 instead.")
5

6 print("The square root of ", x, "is", math.sqrt(x))

In this case, the print function that outputs the square root is the one after the if — not because we left a blank line,
but because of the way the code is indented. Note too that the function call math.sqrt(x) will give an error unless

3.2. Conditionals 35
How to Think Like a Computer Scientist: Learning with Python 3 Documentation, Release 3rd
Edition

we have an import math statement, usually placed near the top of our script.

Python terminology
Python documentation sometimes uses the term suite of statements to mean what we have called a block here. They
mean the same thing, and since most other languages and computer scientists use the word block, we’ll stick with that.
Notice too that else is not a statement. The if statement has two clauses, one of which is the (optional) else
clause.

3.2.7 Chained conditionals

Sometimes there are more than two possibilities and we need more than two branches. One way to express a compu-
tation like that is a chained conditional:

1 if x < y:
2 <STATEMENTS_A>
3 elif x > y:
4 <STATEMENTS_B>
5 else: # x == y
6 <STATEMENTS_C>

Flowchart of this chained conditional

elif is an abbreviation of else if. Again, exactly one branch will be executed. There is no limit of the number of
elif statements but only a single (and optional) final else statement is allowed and it must be the last branch in the
statement:

36 Chapter 3. Program Flow


How to Think Like a Computer Scientist: Learning with Python 3 Documentation, Release 3rd
Edition

1 if choice == "a":
2 function_one()
3 elif choice == "b":
4 function_two()
5 elif choice == "c":
6 function_three()
7 else:
8 print("Invalid choice.")

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the
corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true
branch executes.

3.2.8 Nested conditionals

One conditional can also be nested within another. (It is the same theme of composability, again!) We could have
written the previous example as follows:

Flowchart of this nested conditional

1 if x < y:
2 <STATEMENTS_A>
3 else:
4 if x > y:
5 <STATEMENTS_B>
6 else:
7 <STATEMENTS_C>

3.2. Conditionals 37
How to Think Like a Computer Scientist: Learning with Python 3 Documentation, Release 3rd
Edition

The outer conditional contains two branches. The second branch contains another if statement, which has two
branches of its own. Those two branches could contain conditional statements as well.
Although the indentation of the statements makes the structure apparent, nested conditionals very quickly become very
difficult to read. In general, it is a good idea to avoid them when we can.
Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the
following code using a single conditional:

1 if 0 < x: # Assume x is an int here


2 if x < 10:
3 print("x is a positive single digit.")

The print function is called only if we make it past both the conditionals, so instead of the above which uses two
if statements each with a simple condition, we could make a more complex condition using the and operator. Now
we only need a single if statement:

1 if 0 < x and x < 10:


2 print("x is a positive single digit.")

In this case there is a third option:

1 if 0 < x < 10:


2 print("x is a positive single digit.")

3.2.9 Logical opposites

Each of the six relational operators has a logical opposite: for example, suppose we can get a driving licence when our
age is greater or equal to 18, we can not get the driving licence when we are less than 18.
Notice that the opposite of >= is <.

operator logical opposite


== !=
!= ==
< >=
<= >
> <=
>= <

Understanding these logical opposites allows us to sometimes get rid of not operators. not operators are often quite
difficult to read in computer code, and our intentions will usually be clearer if we can eliminate them.
For example, if we wrote this Python:

1 if not (age >= 18):


2 print("Hey, you're too young to get a driving licence!")

it would probably be clearer to use the simplification laws, and to write instead:

1 if age < 18:


2 print("Hey, you're too young to get a driving licence!")

Two powerful simplification laws (called de Morgan’s laws) that are often helpful when dealing with complicated
Boolean expressions are:

38 Chapter 3. Program Flow

You might also like