-3

Why does it say 'Die eingegebenen Daten haben den falschen Datentyp!' when the datatypes are actually right? Doesn't even work with just matrNr... Although I checked my input of matrNr to be an int?!

class Student:
    def __init__(self):
        self.matrNr = -1
        self.vorname = ''
        self.nachname = ''
        self.gebDatum = []
        self.email = ''
        self.telNr = ''

    def DatenUebergeben(self, matrNr, vorname, nachname, gebDatum, telNr):  
        if matrNr == int and vorname == str and nachname == str and gebDatum == list and telNr == str:
            print('richtige Datentypen!')
        else:
            print('Die eingegebenen Daten haben den falschen Datentyp!')

student1 = Student()
student1.DatenUebergeben(12345,'linda','f',[2,2,1995],'12345')
lindafl0w
  • 3
  • 2
  • Please paste the code into your question and don't link a screenshot. – Kenny Dec 16 '21 at 11:38
  • Does this answer your question? [How do you set a conditional in python based on datatypes?](https://stackoverflow.com/questions/14113187/how-do-you-set-a-conditional-in-python-based-on-datatypes) – MisterMiyagi Dec 16 '21 at 11:44
  • TLDR: Use ``isinstance(matrNr, int)`` instead of ``matrNr == int`` and so on. – MisterMiyagi Dec 16 '21 at 11:45

1 Answers1

0

Background

By checking (for example) matrNr == int you actually compare the variable matNr, which is an int (an instance of <class 'int'>) to the class int (<class 'int'>).

Quick fix

You can use the type()-function to get the type of a variable, resulting in type(matrNr) == int. This does exactly what you are trying to achieve.

Better solution

In Python you can define the types of variables a function accepts by adding : <type> after the argument. The better solution would thus be:

def DatenUebergeben(self, matrNr: int, vorname: str, nachname: str, gebDatum: list, telNr: str):
    # do something
Kenny
  • 530
  • 3
  • 12
  • "In Python you can define the types of variables a function accepts by adding ``: `` after the argument." Adding ``: ``only creates an **annotation**. It does not cause Python to check whether the types are correct. One needs a separate type checker such as MyPy to check such types, and even then they are not sufficient to check user input at runtime. – MisterMiyagi Dec 16 '21 at 12:09