CIT PYTHON COHORT THREE
  • CIT Python Cloud Software Engineering
  • week one
    • What is Python
    • Python Syntax
    • variables
    • Numbers / Integers
  • week Two
    • Control Flow Statements
      • If Statements
      • For Loops
      • While Loops
      • Break and Continue Statements
    • Operators
      • Assignment Operators
      • Arithmetic Operators
      • Comparison Operators
      • Logical Operators
      • Bitwise Operators
      • Identity Operators
      • Membership Operators
    • Data Types
      • Strings
      • Numbers
      • Booleans
      • Lists
      • Dictionaries
      • Tuples
      • Sets
  • Week 3
    • Functions
      • Function Arguments
      • Python Recursion
      • Python Anonymous/Lambda Function
    • Object Oriented Programming
      • Classes
      • Inheritance
      • Polymorphism
      • Abstraction
      • Encapsulation
    • Python Modules
      • Python Packages
      • Python Built-in Modules
      • Python Standard Library
      • Python Third Party Modules
    • Python Exceptions
      • Python Try Except
      • Python Raise
      • Python Assert
      • Python User-defined Exceptions
  • Week 4 - File Handling
  • Week6
    • Data Structures and Algorithms
      • DSA Introduction
      • What is an Algorithm?
      • Data Structures and Types
      • Stack
      • Queue
      • Linked List
      • Bubble Sort Algorithm
      • Selection Sort Algorithm
      • Insertion Sort Algorithm
      • Merge Sort Algorithm
      • Quick Sort Algorithm
  • Week8
    • Cryptography
      • Reverse Cipher
      • Caesar Cipher
      • Hash Functions
        • Applications of Hash Functions
        • Examples of Hash Functions
  • Assignments and Solutions
    • Loops
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. week Two
  2. Control Flow Statements

If Statements

PreviousControl Flow StatementsNextFor Loops

Last updated 11 days ago

Was this helpful?

Often, you need to execute some statements only if some condition holds, or choose statements to execute depending on several mutually exclusive conditions.

The Python compound statement if, which uses if, elif, and else clauses, lets you conditionally execute blocks of statements. Here’s the syntax for the if statement:

if expression:
    statement(s)
elif expression:
    statement(s)
elif expression:
    statement(s)
...
else:
    statement(s)

Below is a flowchart that shows the execution of the if statement:

The elif and else clauses are optional. Note that unlike some languages, Python does not have a switch statement, so you must use if, elif, and else for all conditional processing.

Here’s a typical if statement, demonstrating the preferred multi-line style:

x = 10  # Try changing this value (e.g., -5, 7, 0) to see different outputs
if x < 0:
    print(f"x ({x}) is negative")
elif x % 2 != 0: # Check for odd
    print(f"x ({x}) is positive and odd")
else:
    print(f"x ({x}) is even and non-negative (or zero)")

When there are multiple statements in a clause (i.e., the clause controls a block of statements), the statements are placed on separate logical lines after the line containing the clause’s keyword (known as the header line of the clause) and indented rightward from the header line. The block terminates when the indentation returns to that of the clause header (or further left from there).

While Python allows a single simple statement to follow the : on the same logical line as the header, the separate-line style, as shown above, is generally considered more readable and is recommended. You can use any Python expression as the condition in an if or elif clause.

When you use an expression this way, you are using it in a Boolean context. In a Boolean context, any value is taken as either true or false.

As we discussed earlier, any non-zero number or non-empty string, tuple, list, or dictionary evaluates as true.

Zero (of any numeric type), None, and empty strings, tuples, lists, and dictionaries evaluate as false. When you want to test a value x in a Boolean context, use the following coding style:

if x:

This is the clearest and most Pythonic form. Don’t use:

if x is True:
if x == True:  # Corrected typo and also generally discouraged
if bool(x):

There is a crucial difference between saying that an expression “returns True" (meaning the expression returns the value 1 intended as a Boolean result) and saying that an expression “evaluates as true” (meaning the expression returns any result that is true in a Boolean context).

When testing an expression, you care about the latter condition, not the former.

If the expression for the if clause evaluates as true, the statements following the if clause execute, and the entire if statement ends.

Otherwise, the expressions for any elif clauses are evaluated in order. The statements following the first elif clause whose condition is true, if any, are executed, and the entire if statement ends. Otherwise, if an else clause exists, the statements following it are executed.