Home > Software engineering >  Is this if statement correct?
Is this if statement correct?

Time:03-12

class Person:

        def __init__(self, age, work):
                self.age = age
                self.work = work
        def displayPerson(self):
                print ("Person age: ", self.age, "Person work: ", self.work)

pers1 = Person(24, "data scientist")
pers2 = Person(16, "artist")

pers1.displayPerson()
pers2.displayPerson()

check = input("Input an attribute tho check if it exists: ")

if check = "age":
         hasattr(pers1, age)
elif check = "work":
        hasattr(pers1, work)
else
        print("False.")

CodePudding user response:

You need to change the equal sign to two equal signs for comparisons. One equal sign is used for assignments. You then need to print the hasattr method if you want to see the return value.

CodePudding user response:

When you want to use if to compare if something is equals to something else, you should use == insted of =.

If you use =, you're atributing a value to a variable.

Here's a list of a few comparators: https://www.pythonpool.com/python-comparators/

See if that works:

if check == "age":
         hasattr(pers1, age)
elif check == "work":
        hasattr(pers1, work)
else
        print("False.")

CodePudding user response:

Comparison is done with 2 equal sign, one is for assignation : check == "age"


But the condition shouldn't be on the value given by the user but rather on the hasattr

test_attr = input("Input an attribute tho check if it exists: ")
if hasattr(pers1, test_attr):
    print("Person does have", test_attr)
else:
    print("Person do not have", test_attr)

Also best pratices are to let caller code do the print, and class would implement a representation of themselves

class Person:
    def __str__(self):
        return f"Person: age={self.age} work={self.work}"

print(pers1) # Person: age=24 work=data scientist
print(pers2) # Person: age=16 work=artist

CodePudding user response:

== is a relational operator (Used to check if something is equal to another) while = is an assignment operator (Used to assign values). You should be using == here and not =.

also hasattr will return a boolean(True or False) so you should print it and not just call the function.

if check == "age":
        print(hasattr(pers1, age))
elif check == "work":
        print(hasattr(pers1, work))
else
        print("False.")

You could also improve you're code by doing something like this instead:

if (hasattr(pers1,check)):
    print("True")
else:
    print("False");
  • Related