2.7 Decision Making: The if Statement and Comparison Operators

  • A condition is a Boolean expression with the value True or False.
In [1]:
7 > 4
Out[1]:
True
In [2]:
7 < 4
Out[2]:
False
Algebraic operator Python operator Sample condition Meaning
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
= == x == y x is equal to y
!= x != y x is not equal to y
  • Operators >, <, >= and <= have the same precedence.
  • Operators == and != have the same precedence, which is lower than >, <, >= and <=.
  • It's a syntax error when any of the operators ==, !=, >= and <= contains spaces between its pair of symbols.
In [3]:
7 > = 4
  File "<ipython-input-3-5c6e2897f3b3>", line 1
    7 > = 4
        ^
SyntaxError: invalid syntax

Making Decisions with the if Statement: Introducing Scripts

  • The if statement uses a condition to decide whether to execute a statement (or a group of statements).
  • We’ll read two integers from the user and compare them using six consecutive if statements, one for each comparison operator.
  • When you have many statements to execute as a group, you typically write them as a script stored in a file with the .py (short for Python) extension.
  • To run this example, change to this chapter’s ch02 examples folder, then enter:
    ipython fig02_01.py
  • In IPython interactive mode or in JupyterLab, you can use the command:
    run fig02_01.py
# fig02_01.py
"""Comparing integers using if statements and comparison operators."""

print('Enter two integers, and I will tell you',
      'the relationships they satisfy.')

# read first integer
number1 = int(input('Enter first integer: '))

# read second integer
number2 = int(input('Enter second integer: '))

if number1 == number2:
    print(number1, 'is equal to', number2)

if number1 != number2:
    print(number1, 'is not equal to', number2)

if number1 < number2:
    print(number1, 'is less than', number2)

if number1 > number2:
    print(number1, 'is greater than', number2)

if number1 <= number2:
    print(number1, 'is less than or equal to', number2)

if number1 >= number2:
    print(number1, 'is greater than or equal to', number2)
  • Enter 37 and 42
In [4]:
run fig02_01.py
Enter two integers and I will tell you the relationships they satisfy.
37 is not equal to 42
37 is less than 42
37 is less than or equal to 42
  • Enter 7 and 7
In [5]:
run fig02_01.py
Enter two integers and I will tell you the relationships they satisfy.
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7
  • Enter 54 and 17
In [6]:
run fig02_01.py
Enter two integers and I will tell you the relationships they satisfy.
54 is not equal to 17
54 is greater than 17
54 is greater than or equal to 17

Comments

  • The hash character (#) indicates that the rest of the line is a comment.
  • We begin each script with a comment indicating the script’s file name.
  • A comment also can begin to the right of the code on a given line and continue until the end of that line.

Docstrings

  • The Style Guide for Python Code says each script should start with a docstring that explains the script’s purpose.
  • Often spans many lines for more complex scripts.

Blank Lines

  • Blank lines and space characters to make code easier to read.
  • Together, blank lines, space characters and tab characters are known as white space.
  • Python ignores most white space.

Splitting a Lengthy Statement Across Lines

  • Typically, you write statements on one line.
  • You may spread a lengthy statement over several lines with the \ continuation character.
  • Also can split long code lines in parentheses without using continuation characters (as in the script's first print statement)—this is preferred according to the Style Guide for Python Code.

Reading Integer Values from the User

  • We use built-in functions input and int to prompt for and read two integer values from the user.

if Statements

  • Each if statement consists of the keyword if, the condition to test, and a colon (:) followed by an indented body called a suite.
  • Each suite must contain one or more statements.

Suite Indentation

  • Python requires you to indent the statements in suites.
  • The Style Guide for Python Code recommends four-space indents.

Confusing == and =

  • Using the assignment symbol (=) instead of the equality operator (==) in an if statement’s condition is a common syntax error.

Chaining Comparisons

  • You can chain comparisons to check whether a value is in a range.
In [7]:
x = 3
In [8]:
1 <= x <= 5
Out[8]:
True
In [9]:
x = 10
In [10]:
1 <= x <= 5
Out[10]:
False

Precedence of the Operators We’ve Presented So Far

Operators                 Grouping          Type
() left to right parentheses
** right to left exponentiation
*     /     //     % left to right multiplication, true division, floor division, remainder
+     left to right addition, subtraction
>     <=     <     >= left to right less than, less than or equal, greater than, greater than or equal
==     != left to right equal, not equal

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 2 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.