Classes and loops
Related code
class Student: """Represents a student. attributes: name, grade """ class University: """Represents a university. attributes: name, students """ def print_student(st): print(f"Name: {st.name}, Grade: {st.grade}") hp = University() hp.name, hp.students = "Hasan Prishtina", []
In real-world programs, we rarely deal with just one object. A zoo has many animals. A school has many students. An app has many users. Loops allow us to create, update, and interact with all those objects efficiently.
add_students
takes a university and a list of dictionaries,
it iterates the list, creates students and adds them to university.
def add_students(uni, students): for student in students: st = Student() st.name = student['name'] st.grade = student['grade'] uni.students.append(st)
print_university
takes a university, it iterates its students and prints each student detail.
def print_university(uni): print(uni.name) print("=========================") print() for st in uni.students: print_student(st)
... students = [ {"name": "Albert Krasniqi", "grade": 6}, {"name": "Abetare Krasniqi", "grade": 7}, {"name": "Bahri Berisha", "grade": 6}, ] add_students(hp, students) print_university(hp)
Hasan Prishtina ========================= Name: Albert Krasniqi, Grade: 6 Name: Abetare Krasniqi, Grade: 7 Name: Bahri Berisha, Grade: 6
Exercises
class Book: """Represents a book. attributes: title: str, author: str """ class Library: """Represents a library. attributes: name: str, books: list[Book] """ b = Book() b.title = "Toke e pergjakur" b.author = "Nazmi Rrahmani" hs = Library() hs.name = "Hivzi Sylejmani" hs.books = [] book_list = [ {"title": "Toke e pergjakur", "author": "Namzmi Rrahmani"}, {"title": "Lugjet e verdha", "author": "Rexhep Hoxha"}, ]
Define a function add_books(library: Library, book_list: list[dict]) that creates books from book_list and adds them to the library.
class Player: """Represents a player. attributes: name: str, position: str """ class Team: """Represents a team. attributes: name: str, players: list[Player] """
Write a function, print_team(team) that prints the name of the team
and all its players' names and positions as follows:
AC Milan Alessandro Nesta - Defender Paolo Maldini - Defender Andriy Shevchenko - Forward
class Item: """Represents an item. attributes: name: str, price: float class Cart: """Represents a cart. attributes: items: list[Item] """
Write a function, total_price(cart: Cart), that returns the sum of prices of all items in cart.
class Player: """Represents a player. attributes: name: str, position: str, goals: int """ class Team: """Represents a team. attributes: name: str, players: list[Player], goals: int """
Write a function, set_total_goals(team: Team), that sets team's total goals to team's goals attribute.
class Movie: pass class User: pass movies = [ ("Inception", "alice", 9), ("The Shawshank Redemption", "bob", 10), ("The Godfather", "bob", 10), ("Interstellar", "charlie", 8), ("The Shawshank Redemption", "diana", 9), ] def populate(data): ratings = [] for mt, usr, rt in data: m = Movie() m.title = mt u = User() u.name = usr ratings.append((u, m)) return ratings ratings = populate(movies) a = ratings[0][0].name b = ratings[-1][-1].title
At the end of execution of the above script, what is value of?
a: | |
b: |
Exercises
class Library: """Represents a library. attributes: name, books """ class Book: """Represents a book. attributes: title, author """ b = Book() b.title = "Toke e pergjakur" b.author = "Nazmi Rrahmani" hs = Library() hs.name = "Hivzi Sylejmani" hs.books = []
Write a function, print_library(library),
that prints the library name and its books as follows:
Hivzi Sylejmani ======================== Toke e pergjakur - Nazmi Rrahmani Lugjet e verdha - Rexhep Hoxha ...
class Employee: """Represents an employee. attributes: name: str """ class Company: """Represents a company. attributes: name: str, employees: list[Employee] """ employees_list = ["Emma Johnson", "Liam Martinez", "Sophia Williams"]
Write a function, add_employees(company: Company, employees_list: list[str]), that takes a list of employee names and adds them as Employee instances to the company.
class Player: """Represents a player. attributes: name: str, position: str, goals: int """ class Team: """Represents a team. attributes: name: str, players: list[Player] """
Write a function, total_goals(team) that returns the sum of goals scored by the whole team.
class Account: """Represents a bank account. attributes: owner: str, balance: float """ class Bank: """Represents a bank. attributes: name: str, accounts: list[Account], total: float """
Write a function, set_total_value(bank: Bank), that sets bank's total value to bank's total attribute.
class Movie: pass class User: pass movies = [ ("Inception", "alice", 9), ("The Shawshank Redemption", "bob", 10), ("The Godfather", "bob", 10), ("Interstellar", "charlie", 8), ("The Shawshank Redemption", "diana", 9), ] def populate(data): ratings = [] for mt, usr, rt in data: m = Movie() m.title = mt u = User() u.name = usr ratings.append((u, m)) return ratings ratings = populate(movies) a = ratings[1][0].name b = ratings[0][1].title
At the end of execution of the above script, what is value of?
a: | |
b: |