Search code examples
pythonpython-3.xexceptiontry-catchassertions

Python 3.x A program thats control if some requirments true


My purpose with this program is to take input from student and make sure that he/she typed 3 digit number. Neither less than 3 or greater than 3 and it shouldnt be string. All this above if something wrong, program should ask again until its become true

def studentID():
       try:
           number=int(input("sutedent IDS:"))
           try:
                assert len(number)==3

           except AssertionError:
               print("Must be 3 digit number.")
               studentID()

       except ValueError:
           print("Please enter an integer.")
           studentID()

       except TypeError:
           print("What is wrong with you?")
           studentID()

Solution

  • ints don't have a len. You'll have to convert it back to a string to check its length.

    def studentid():
        try:
            num = int(input('student ID:'))
            if len(str(num)) != 3:
                print('Please enter a 3-digit number')
                return studentid()
            return num
        except ValueError:
            print('Please enter a 3-digit number')
            return studentid()
    

    You also probably want to return the num to the caller. Note that we cast the input to an int then back into a string. This is because in some recent versions of Python (3.6+), you can have underscores in int literals, so int('1_2') would be a valid 3 character input that evaluates to a 2 digit number