Home > Blockchain >  Python - how to correctly implement TypeError
Python - how to correctly implement TypeError

Time:04-28

try:
   Name = input("enter name")
except TypeError:
   print("Please enter letters")

Even when I enter numbers, the message doesn't print.

CodePudding user response:

there wont be a type error because you entered a string and save it to a string. TypeError is an exception in Python programming language that occurs when the data type of objects in an operation is inappropriate. For example, If you attempt to divide an integer with a string, the data types of the integer and the string object will not be compatible. (from: here)

look here for a solution: how to find if there is a number in a string

CodePudding user response:

The main problem is that you never check whether numbers are there.

Try something like this:

while True: #loop while input invalid
   try:
      Name = input("enter name")
      if not Name.isalpha(): # checks whether Name is not letters only
         raise TypeError #Raise error if numbers are there
      else:
         break #Else, exit the loop

   except TypeError:
      print("Please enter letters")
  • Related