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.
- Yea ok so that works. But we needed 2 print statements and had to know how many houses were in our database…this is where loops come in
- 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
- 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?
- Ok but how do we know that worked? Lets leave the path the same but look instead for the living room
Combo
- Using the same code lets do a little bit more to it. Use a loop and conditional.
Code Links