☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 3 : Processing : Decisions : if Statements

if Statements

Subscribe Contact


Contents

Overview

The most fundamental decision construct we have in Python is the if statement, which will execute a block (one or more lines) of code if a specified condition evaluates to True. In English, we could describe this concept as "if this specific thing is true, then do the following." As an example, "if your score is 100, then print 'Perfect!'" In Python code, we would write this as:

if score == 100:
      print("Perfect!")

There are some new syntactic details to consider in this code (which we will address below) but, for now, pay more attention to the concept of "if this then do that." Keeping this in mind i sthe start of constructing decisions in Python.

v

General Form

The general form of the if statement looks like this:

if condition:
      code_block

The first key details to notice about this general form are the following:

Concept: Indentation

In Python, indentation is significant for certain syntax structures. Notice in the general form below, that code_block is indented. This is a requirement in Python if statements. All code that is part of the code block must be indented, this is how the interpreter knows what code is included in the block of code to run when the if statement condition evaluates to True.

if condition:
    code_block_based_on_true_condition
else:
    code_block_based_on_false_condition

Concept: Code Block

A code block is a group of one or more statements that are grouped together and executed as a single unit. Code blocks are defined by their indentation level, which is typically done using spaces or tabs. Proper indentation is crucial in Python because it determines the scope of statements within a block. For example, when writing an if statement or a loop, the indented code underneath it forms a code block. This indentation-based structure enhances code readability and ensures that Python interprets the code correctly. Understanding code blocks is fundamental for organizing and structuring Python programs, making them more organized and easier to maintain.

Figure 1 depicts the general form of the if statement as a flow chart. The execution flow represents the flow of the program up to the point of the if condition. When the if condition is evaluated by the interpreter, the result will be either True or False. If the result is True then execution flow moves into the code_block and that code runs. When it is finished flow continues to the next statement after the indented code_block. If, however, the if condition returns False, then the code_block is skipped and execution flow continues to the next statement after the indented code_block. Let's take a look at an example:

low = 1
high = 10
secret_number = 8
print("Program started.")
guess = int(input("Enter your guess between " + str(low) + " and " + str(high) + ": "))
if guess == secret_number:
    print("You guessed right!")
print("Program complete.")

And running the program looks like this:

Program started.
Enter your guess between 1 and 10: 8
You guessed right!
Program complete.



Figure 1: General Form of an if Statement

Notes:

In the example above we used the double-equal comparison symbol in our if statement condition. That symbol is one of the numerous comparison operators that exist in Python. Here is a list of all of them:

Comparison Operators

Operator Comparison Description
== Equal The double-equal symbol compares the value with the value. If they are equal, then it results in True. If the comparison is not equal, then it results in False.
Note: A common mistake in coding is to use the single-equal sign (=) instead of the double-equal (==). This mistake can cause significant problems because instead of making a comparison, the single-equal assigns the values of the right side to the left side.

Example:
x = 10
y = 20
if x == y:
Condition Result: False

!= Not Equal This comparison operator is the opposite of the equal operator above. It compares the value with the value. If they are not equal, then it results in True. If the comparison is equal, then it results in False.

Example:
x = 10
y = 20
if x != y:
Condition Result: True

> Greater Than This comparison operator checks if the value is greater than (determined by the data type) the value. If the is greater, then it results in True. If the is not greater than the right side, then it results in False.

Example:
x = 10
y = 20
if x > y:
Condition Result: False

< Less Than This comparison operator checks if the value is less than (determined by the data type) the value. If the is less, then it results in True. If the is not less than the right side, then it results in False.

Example:
x = 10
y = 20
if x < y:
Condition Result: True

>= Greater Than or Equal To This comparison operator checks if the value is greater or equal to (determined by the data type) the value. If the is greater or equal to, then it results in True. If the is not greater or equal to than the right side, then it results in False.

Example:
x = 10
y = 20
if x >= y:
Condition Result: False

<= Less Than or Equal To This comparison operator checks if the value is less than or equal to (determined by the data type) the value. If the is less than or equal to, then it results in True. If the is not less than or equal to the right side, then it results in False.

Example:
x = 10
y = 20
if x <= y:
Condition Result: True

Compound Conditions

The if statement examples provided above contain a single condition (x == y for example), however, our conditions can be more complex and make several comparisons in one compound condition. To create more complex conditions, we need a way to connect more than one condition together, which we do with logical operators. Here is a list of the logical operators in Python:

Logical Operators
Operator Description
and The and operator compares the condition to its left with the condition to its right, if both conditions are True then the compound condition is True. If either of the two conditions or both, are False, then the compound condition is False.

Examples:
x = 10
y = 20
z = 30
if (x < y) and (z > x):
Condition Result: True
x = 10
y = 20
z = 30
if (x < y) and (z < x):
Condition Result: False
x = 10
y = 20
z = 30
if (x < y) and (z > y) and (z == (x + y)):
Condition Result: True

or The or operator compares the condition to its left with the condition to its right, if either of the conditions is True then the compound condition is True. In a compound condition when more than two conditions, each separated by an or, as long as any one of the conditions is True then the compound condition is True.

Examples:
x = 10
y = 20
z = 30
if (x < y) or (z > x):
Condition Result: True (both are True)
x = 10
y = 20
z = 30
if (x < y) or (z < x):
Condition Result: True (the first condition is True)
x = 10
y = 20
z = 30
if (x < y) or (z > y) or (z == (x + y)):
Condition Result: True (at least one condition is True)

not The not operator reverses the result of the compound condition, so if the compound returns True the not operator will reverse it to False, and if the compound condition returns False the not operator will reverse it to True. In the examples below, notice that the compound condition is placed inside parenthesis and the not operator precedes that set of parenthesis.

Examples:
x = 10
y = 20
z = 30
if not((x < y) or (z > x)):
Condition Result: False
x = 10
y = 20
z = 30
if not((x < y) or (z < x)):
Condition Result: False
x = 10
y = 20
z = 30
if not((x < y) or (z > y) or (z == (x + y))):
Condition Result: False

Practice Problem

Problem 1

if Statement w/Compound Condition: Write a Python program that prompts the user for their age. If their age is between 40 and 50 inclusive, print "You are middle-aged."

Please enter your age: 43
You are middle-aged.


The if statement works well when we have a single decision to make. That decision can be a single condition or a compound condition. However, the simple if only executes code if the condition result is True. We often need one code_block if the result is True and a different block of code if the result is False. To accomplish this, we will learn the if-else statement on the next page.



 





© 2023 John Gordon
Cascade Street Publishing, LLC