liveBook · Manning

Conditional logic

As explained in Get Programming: Learn to code with Python

A nested conditional is a conditional statement placed inside another conditional's code block so that its evaluation depends on the outer conditional.

Conditional logic lets a program decide which lines to run. An if statement asks a true-or-false question, called a Boolean expression. If the answer is True, Python runs the indented code block; if it is False, Python skips that block and continues afterward. The goal is to choose the right path through a program, then trace which lines that path executes. section 13.1 section 13.2

One decision

num = int(input("Enter a number: ")) if num > 0: print("num is positive") print("finished comparing num to 0") The first print runs only for a positive number. The last print is not indented, so it runs whether the condition is true or false. section 13.2

A nested conditional is an if statement inside another conditional’s code block. Python reaches the inner question only when it enters the outer block. The inner if has its own, further-indented block. That differs from two if statements in a series: Python reaches each of those questions in turn. Use == to check equality; a single = assigns a value. section 13.3

Listing 13.4. Combining conditionals by nesting or by putting them in series
Nested code                                   Unnested code
num_a = int(input("Number? "))                num_a = int(input("Number? "))
num_b = int(input("Number? "))                num_b = int(input("Number? "))
if num_a < 0:                      #1          if num_a < 0:             #1
    print("num_a: is negative")                   print("num_a is negative")
    if num_b < 0:                  #2          if num_b < 0:             #2
        print("num_b is negative")                print("num_b is negative")
print("Finished")                  #3           print("Finished")        #3

Compare the two-number programs. When the first number is positive and the second is negative, only the unnested version can print that the second number is negative: the nested version never reaches its inner check. section 13.3

For different answers to one decision, use if with elif and, optionally, else. Python runs the first matching branch, rather than every matching branch. For example, a number can be reported as positive, negative, or zero. By contrast, separate if statements each get their own check. section 14.2 section 13.3

You can also combine questions inside one condition with and or or. For example, if num_a < 0 and num_b < 0 enters its block only when both tests are true. Write each test explicitly: if num_a and num_b < 0 does not check whether both numbers are negative. When conditions grow complicated, pay attention to operator precedence. section 14.1

Listing 15.2. An adventure with only one choice
do = input(":: ")                                                  #1
if do == "LOOK":                                                   #2
    print("You are stuck in a sand ditch.")
    print("Crawl out LEFT or RIGHT.")

    do = input(":: ")                                              #3
    if do == "LEFT":                                               #4
        print("You make it out and see a ship!")
        print("You survived!")
    elif do == "RIGHT":                                            #5
        print("No can do. That side is very slippery.")
        print("You fall very far into some weird cavern.")
        print("You do not survive :(")
else:                                                              #6
    print("You can only do actions shown in capital letters.")
    print("Try again!")

Follow this short adventure one choice at a time. A LEFT or RIGHT check happens only after the player enters LOOK, showing how nested conditionals make subpaths within a chosen path. section 15.2

Quick check: if the player does not enter LOOK, will the LEFT condition be tested? No—the program skips the outer block. For a larger adventure, sketch the possible paths, then run and test choices along each path. section 15.2 section 15.3 section 13.4

How Get Programming: Learn to code with Python covers it

How deep it goes
Works through single, sequential, nested, and alternative branches, including indentation and Boolean combinations; it does not examine Python internals.
Examples
Traces positive-number checks, nested negative-number checks, and choices in a choose-your-own-adventure program.
What it assumes
Assumes familiarity with statements, expressions, and variables while introducing Boolean decisions and if syntax in plain language.
What you can do after
Build it from scratch by writing and testing Python conditionals that create different paths through a program.
How it connects
Connects Boolean expressions, code blocks, operator precedence, flowcharts, user input, and branching.

Also explained in

Compare how 21 books explain conditional logic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.