Marco Hauser
Marco Hauser

Reputation: 27

Python Class For loop

class Person:
    def __ini‎t__(sel‎f, age):
        self._age = age

    @prop‎‎er‎t‎y
    def age(self):
        return self._a‎g‎e

person‎s = [Pe‎r‎son(20), Pe‎‎r‎s‎o‎n(30), Person‎(19), Pers‎on(17), Per‎son(15), Per‎‎son(25)]  

result = persons[0]

for person in persons:
    if person.age < result.age:
        result = person

Can someone please explain to me, what happens in this for loop? As far as I understand it checks, if the input of age is smaller than the result and if so, it "puts" it into the result variable. The solution states 15 but how do we get there?

Upvotes: 1

Views: 141

Answers (2)

user16716191
user16716191

Reputation:

The loop cycles though the persons list and then compares their age Person.age to the Person's age in results result.age. The result at the start is set to persons[0] or Person(20), if it finds someone who is younger aka person.age < result.age the result becomes the "person". So the loop is finding the youngest person in the list.

Upvotes: 2

mattdood
mattdood

Reputation: 48

For things like this it is sometimes easier to step through the problem by writing out what is happening.

So we know we're using a list of Person objects, which have an assigned age that we can retrieve.

Starting the loop if we plug in what we have:

result = persons[0] # first person in the list, Person.age = 20

for person in persons:
   if person.age < result.age:
       result = person.age

Iteration 1:

result = 20
if 20 < 20: # this is false
    result = 20

Iteration 2:

result = 20
if 30 < 20: # this is false
    result = 30

Iteration 3:

result = 20
if 19 < 20: # this is true, result is reassigned
    result = 19

Etc. for all items in the list.

Upvotes: 0

Related Questions