Try   HackMD
tags: Lesson Notes Python Fundamentals PythonFlask2021

Loops and Conditionals

If you don't like loops and conditionals sorry, but this is a fact of a programmers life. It is just something we have to do. Looping through data and checking to see if something is there or not just happens to be a part of your life now.

Starter Code:

data = [
    {
        "house": "First House", "floors": [
            {
                "floor": "1st Floor", "rooms": [
                    {"room": "Living Room", "contents": ['couch', 'TV', 'painting']}, 
                    {"room": "Kitchen", "contents": ['table', 'chairs', 'stove', 'fridge']}, 
                    {"room": "Bathroom", "contents": ['sink', 'mirror', 'toilet']}
                ]
            }, 
            {
                "floor": "2nd Floor", "rooms": [
                    {"room": "Master Bedroom", "contents": ['bed', 'dresser', 'clothes']}, 
                    {"room": "Kids Room", "contents": ['bed', 'dresser', 'desk', 'clothes']}, 
                    {"room": "Bathroom", "contents": ['tub', 'sink', 'toilet', 'mirror']}
                ]
            }
        ]
    },
    {
        "house": "Second House", "floors": [
            {
                "floor": "1st Floor", "room": [
                    {"room": "Den", "contents": ['Bar', 'Bar Stools', 'TV', 'Couch']},
                    {"room": "Living Room", "contents": ['couch', 'TV', 'rug', 'end tables']}
                ]
            },
            {
                "floor": "2nd Floor", "rooms": [
                    {"room": "Bedroom", "contents": ['bed', 'dresser', 'clothes']},
                    {"room": "Bathroom", "contents": ['sink', 'toilet', 'tub']}
                ]
            }
        ]
    }
]

Loops:

  • Ok so we have our starter code that contains data on 2 houses. So lets start our loop demo by printing just the 2 house names.
print(data[0]['house'])
print(data[0]['house'])

# Output:
First House
Second House
  • Yea ok so that works. But we needed 2 print statements and had to know how many houses were in our databasethis is where loops come in
def houseNames(house):
    for h in house:
        print("Printing house names: ", h['house'])

houseNames(data)

# Output:
Printing house names:  First House
Printing house names:  Second House
  • Ok yes a little more code but now no matter how big our database is we can call this function and get all the house names.
  • So lets print all the house names and floor names
def allFloors(data):
    for d in data:
        print("House: ", d['house'])
        for f in d['floors']:
            print("Floors: ", f['floor'])
            
allFloors(data)

# Output:
House:  First House
Floors:  1st Floor
Floors:  2nd Floor
House:  Second House
Floors:  1st Floor
Floors:  2nd Floor
  • Ok got it. The key is knowing how to access each item that you want to print.

Conditionals:

  • Ok so day we want to check to make sure the Den is listed in the right house and the right floor?
def printDen(data):
    if data[1]['floors'][0]['rooms'][0]['room'] == 'Den':
        print("The Den is at this spot")
    else:
        print('Sorry you did not find the den')

printDen(data)

# Output:
"The Den is at this spot"
  • Ok but how do we know that worked? Lets leave the path the same but look instead for the living room
def printLivingRoom(data):
    if data[1]['floors'][0]['rooms'][0]['room'] == 'Living Room':
        print("You have found the living room")
    else:
        print('Sorry you found a different room')
        
printLivingRoom(data)

# Output:
'Sorry you found a different room'
  • Not too bad I guess.

Combo

  • Using the same code lets do a little bit more to it. Use a loop and conditional.
def loopsConditional(data, a):
    for d in data:
        print("Print me the house name please: ", d['house'])
        if d['house'] == a:
            for f in d['floors']:
                print("Floors: ", f['floor'])
        else:
            print('Sorry this is not the house you are looking for')

loopsConditional(data, "Second House")

# Output:
Print me the house name please:  First House
Sorry this is not the house you are looking for
Print me the house name please:  Second House
Floors:  1st Floor
Floors:  2nd Floor

Code Links