Home > Mobile >  Can't get if to use Object variable as parameter
Can't get if to use Object variable as parameter

Time:05-14

Okay, so this is my code:

class Alguien:
    def __init__(self, age, genre):
        self.age=age
        self.genre=genre

#ejercicio 1

def ejercicios():
    a=0
    personas=[object]*100
    contHombre=0
    contMujer=0
    mayEighteen=0
    while a<100:
        edad=randint(0,100)
        genero=randint(0,1)
        personas[a]=Alguien(edad, genero)
        if personas[a].genre==1:
            contHombre =1
        elif personas[a].genre==0:
            contMujer =1
        elif personas[a].age>18:
            mayEighteen =1
        
        a =1

    print(f"{mayEighteen}")

ejercicios()

I'm learning python, and I'm trying to use this class "Alguien" to set age and genre for a list of a hundred people. For some reason, it does recognize the value of genre in the If, but it doesn't recognize the value of age. This is the part of the code giving me problems:

elif personas[a].age>18:
    mayEighteen =1

a =1

print(f"{mayEighteen}")

Where personas[a].age will always be 0. Please help ^^

CodePudding user response:

elif is only executed if the previous if and elif were false. Since either genre == 1 or genre == 0 will be true, it will never perform the age > 18 test.

Use a separate if for that rather than elif.

You should also use else: instead of elif when the second condition is the opposite of the first.

def ejercicios():
    a=0
    personas=[]
    contHombre=0
    contMujer=0
    mayEighteen=0
    for a in range(100):
        edad=randint(0,100)
        genero=randint(0,1)
        personas.append(Alguien(edad, genero))
        if personas[a].genre==1:
            contHombre =1
        else:
            contMujer =1
        if personas[a].age>18:
            mayEighteen =1
  • Related