Tech With Tim Logo
Go back

Chained Conditionals & Nested Statements

Chained Conditionals

Chained conditionals are simply a "chain" or a combination or multiple conditions. We can combine conditions using the following three key words:

  • and
  • or
  • not

The and keyword allows us to check if two conditions are true. If they are both true then the entire condition is true. If one or both of them are false then the entire condition is false.

The or keyword allows us to check if one of two conditions is true. If one or both of the conditions are true then then entire condition will be true. If both of the conditions are false then the entire condition is false.

The not keyword allows us to check if an entire condition is false. If the condition is false it will result in a true value. If the condition is true it will give us a false value (you can think of it as reversing the condition).

True and False  # This gives False
True and True   # This gives True
False and False # This gives False

True or False   # This gives True
True or True    # This gives True
False or False  # This gives False

not True        # This gives False
not False       # This gives True

We can also combine the use of these keywords to create longer conditions:

(True or False) and False  # This is False
False and True and True    # This is False
(True or False) and True   # This is True
True and not(False)        # This is True

not (1 > 2 and 2-7 == -5)   # This is True

Of course we can combine this with our knowledge of if statements to check multiple conditions in one if:

food = input("What is your favorite food? ")
drink = input("What is your favorite drink? ")

if food == "pizza" and drink == "juice":
    print("Those are my favorite as well!")
else:
    print("One of those is not my favorite")

Nested Statements

Now that we've learned about some basic logic and control structures in python we can move on to nesting. Nesting is simply putting code inside of other code. For example placing an if statement inside of an already existing if statement.

answer = input("What is your age? ")

if int(answer) >= 18:
    answer = input("What country do you live in? ")
    if answer == "canada":
        print("Me as well!")
    else:
        print("Oh, I do not live there.")

There is no limit to the amount of times that we can nest. We just have to be sure that we are aware of our indentation.

Design & Development by Ibezio Logo