0% found this document useful (0 votes)
11 views

3.2 Logical Operators: True True

The document discusses logical operators and conditional execution in Python. It defines logical operators like and, or, and not and describes how conditional statements like if, elif, and else work. It also covers nested conditional statements and using try and except to catch exceptions.

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)
11 views

3.2 Logical Operators: True True

The document discusses logical operators and conditional execution in Python. It defines logical operators like and, or, and not and describes how conditional statements like if, elif, and else work. It also covers nested conditional statements and using try and except to catch exceptions.

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

32 CHAPTER 3.

CONDITIONAL EXECUTION

3.2 Logical operators

There are three logical operators: and, or, and not. The semantics (meaning) of
these operators is similar to their meaning in English. For example,
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 of the conditions is true, that is, if the
number is divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so not (x > y) is true if
x > y is false; that is, if x is less than or equal to y.
Strictly speaking, the operands of the logical operators should be boolean expres-
sions, but Python is not very strict. Any nonzero number is interpreted as “true.”

>>> 17 and True


True

This flexibility can be useful, but there are some subtleties to it that might be
confusing. You might want to avoid it until you are sure you know what you are
doing.

3.3 Conditional execution

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

if x > 0 :
print('x is positive')

The boolean expression after the if statement is called the condition. We end the
if statement with a colon character (:) and the line(s) after the if statement are
indented.

Yes
x>0

print(‘x is postitive’)

Figure 3.1: If Logic


3.4. ALTERNATIVE EXECUTION 33

If the logical condition is true, then the indented statement gets executed. If the
logical condition is false, the indented statement is skipped.
if statements have the same structure as function definitions or for loops1 . The
statement consists of a header line that ends with the colon character (:) followed
by an indented block. Statements like this are called compound statements because
they stretch across more than one line.
There is no limit on the number of statements that can appear in the body, but
there must be at least one. Occasionally, it is useful to have a body with no
statements (usually as a place holder for code you haven’t written yet). In that
case, you can use the pass statement, which does nothing.

if x < 0 :
pass # need to handle negative values!

If you enter an if statement in the Python interpreter, the prompt will change
from three chevrons to three dots to indicate you are in the middle of a block of
statements, as shown below:

>>> x = 3
>>> if x < 10:
... print('Small')
...
Small
>>>

When using the Python interpreter, you must leave a blank line at the end of a
block, otherwise Python will return an error:

>>> x = 3
>>> if x < 10:
... print('Small')
... print('Done')
File "<stdin>", line 3
print('Done')
^
SyntaxError: invalid syntax

A blank line at the end of a block of statements is not necessary when writing and
executing a script, but it may improve readability of your code.

3.4 Alternative execution


A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. The syntax
looks like this:
1 We will learn about functions in Chapter 4 and loops in Chapter 5.
34 CHAPTER 3. CONDITIONAL EXECUTION

if x%2 == 0 :
print('x is even')
else :
print('x is odd')

If the remainder when x is divided by 2 is 0, then we know that x is even, and the
program displays a message to that effect. If the condition is false, the second set
of statements is executed.

No Yes
x%2 == 0

print(‘x is odd’) print(‘x is even’)

Figure 3.2: If-Then-Else Logic

Since the condition must either be true or false, exactly one of the alternatives will
be executed. The alternatives are called branches, because they are branches in
the flow of execution.

3.5 Chained conditionals


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

if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')

elif is an abbreviation of “else if.” Again, exactly one branch will be executed.
There is no limit on the number of elif statements. If there is an else clause, it
has to be at the end, but there doesn’t have to be one.

if choice == 'a':
print('Bad guess')
elif choice == 'b':
print('Good guess')
elif choice == 'c':
print('Close, but not correct')
3.6. NESTED CONDITIONALS 35

!
x<y print(‘less’)

!
x>y print (‘greater’)

print(‘equal’)

Figure 3.3: If-Then-ElseIf Logic

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.6 Nested conditionals


One conditional can also be nested within another. We could have written the
three-branch example like this:

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')

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

if 0 < x:
if x < 10:
print('x is a positive single-digit number.')

The print statement is executed only if we make it past both conditionals, so we


can get the same effect with the and operator:
36 CHAPTER 3. CONDITIONAL EXECUTION

Yes No
x == y

Yes No
x<y

print(‘equal’)
print(‘less’) print’‘greater’)

Figure 3.4: Nested If Statements

if 0 < x and x < 10:


print('x is a positive single-digit number.')

3.7 Catching exceptions using try and except


Earlier we saw a code segment where we used the input and int functions to read
and parse an integer number entered by the user. We also saw how treacherous
doing this could be:

>>> prompt = "What is the air velocity of an unladen swallow?\n"


>>> speed = input(prompt)
What is the air velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int() with base 10:
>>>

When we are executing these statements in the Python interpreter, we get a new
prompt from the interpreter, think “oops”, and move on to our next statement.
However if you place this code in a Python script and this error occurs, your script
immediately stops in its tracks with a traceback. It does not execute the following
statement.
Here is a sample program to convert a Fahrenheit temperature to a Celsius tem-
perature:

inp = input('Enter Fahrenheit Temperature: ')


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

# Code: http://www.py4e.com/code3/fahren.py

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy