24  Control Flow Exercise

24.1 For Loop

24.1.1 Meaw

meaw(): using for loop

def meaw(n):
    for _ in range(n):
        print("Meaw")

let’s print “meaw” 3 times

meaw(3)
Meaw
Meaw
Meaw

meaw(): pythonista way

def meaw(n):
    print("Meaw\n" * n, end="")
meaw(4)
Meaw
Meaw
Meaw
Meaw

24.1.2 Hogwarts

24.1.2.1 List of Students

students = ["Hermione", "Harry", "Ron"]
students
['Hermione', 'Harry', 'Ron']
for student in students:
    print(student)
Hermione
Harry
Ron

24.1.2.2 Dictionary of Students

students = [
    {"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
    {"name": "Harry", "house": "Gryffindor", "patronous": "Stag"},
    {"name": "Draco", "house": "Slytherin", "patronous": None}
]

Iterate though array of student (row by row)

for student in students:
    print(student["name"], student["house"], sep=", ")
Hermione, Gryffindor
Harry, Gryffindor
Draco, Slytherin

Define a function to print information from each student

def print_student_info(i):
    print("Student No.", i + 1)
    for k, v in students[i].items() :
        print("- ", k, ": ", v)
print_student_info(0)
Student No. 1
-  name :  Hermione
-  house :  Gryffindor
-  patronus :  Otter

Now, print information from all students

for i in  range(len(students)):
    print_student_info(i)
Student No. 1
-  name :  Hermione
-  house :  Gryffindor
-  patronus :  Otter
Student No. 2
-  name :  Harry
-  house :  Gryffindor
-  patronous :  Stag
Student No. 3
-  name :  Draco
-  house :  Slytherin
-  patronous :  None