Create a class called Rectangle. Its __init__ takes width and height and stores four attributes: self.width and self.height self.area — width × height self.perimeter — 2 × (width + height) Create r = Rectangle(5, 3) and print its area and …
Create a class called ShopItem: __init__ takes name and price and stores them as self.name and self.price. It also sets self.in_stock = True for every new item (not a parameter). Then create item = ShopItem(“Bread”, 10) and print: Bread costs …
The Book class can already be borrowed. Add a new method called give_back that sets available back to True. Copy the style of borrow. Then, using the book object, print its status, borrow it, print again, give it back and …
The class City is already written for you. Use it to: Create an object called asmara with the name “Asmara” and the region “Maekel”. Create an object called massawa with the name “Massawa” and the region “Northern Red Sea”. Call …
Write two recursive functions (no loops and no ** operator — each function must call itself): power(base, exponent) returns base to the power of exponent (a whole number 0 or more). Base case: any number to the power 0 is …
Write a recursive function sum_to(n) that returns the sum of all whole numbers from 1 to n. For example sum_to(4) is 4 + 3 + 2 + 1 = 10. Base case: sum_to(0) returns 0. Recursive case: sum_to(n) is n …
Products are stored as (name, price) tuples. Write two functions with def that use lambdas inside: sort_by_price(products) returns a new list sorted from cheapest to most expensive (use sorted() with a lambda key). Do not change the original list. cheap_names(products, …
Using lambda (not def), create: square — returns a number multiplied by itself is_even — returns True if a number is even, otherwise False Then use them with map() and filter() on numbers = [1, 2, 3, 4, 5, 6] …
Write two functions: build_profile(name, **details) returns a dictionary that contains the key “name” plus every keyword argument. For example build_profile(“Selam”, city=”Asmara”, age=16) returns {‘name’: ‘Selam’, ‘city’: ‘Asmara’, ‘age’: 16}. count_args(*args, **kwargs) returns a tuple: (number of positional arguments, number of …
Define average(*numbers) that accepts any number of numbers and returns their average. If no numbers are given, return 0. Print average(70, 80, 90). Expected output: 80.0 The checker will also try average(5), average() and a list unpacked with *.
