Many brands sell the same product, stored in two parallel lists: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.
You start with:
brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
ratings = [4, 5, 3, 5, 4]
Build:
1. MegaCorp (5)
Rules:
- Keep the position of the best brand so far in
best_index, starting at0, and scan the positions from1to the end with a loop. - Update
best_indexonly on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorpat position 1, notNeoByteat position 3). - Format the winner as
"1. Brand (rating)"and store it inoutput.
Walk the positions with
for i in range(1, len(ratings)): and compare each rating with the best one so far.
In Python a number must go through
str() before it can be joined to text.
brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
ratings = [4, 5, 3, 5, 4]
best_index = 0
for i in range(1, len(ratings)):
if ratings[i] > ratings[best_index]:
best_index = i
output = "1. " + brands[best_index] + " (" + str(ratings[best_index]) + ")"
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
