Search code examples
pythonif-statementsyntaxtry-catch

Syntax error for a simple try-exception-if


I get an error when simulating the following simple code in python:

try:
    name = input()
    #your code goes here
    
    if len(name) < 4: raise NameError("error")
except:
    print("Invalid Name")

The error message is here:

if len(name) < 4: raise NameError("error")
^
Syntax error: invalid syntax

Best regards, Thank you


Solution

  • As you can see in the comments following the question, some of compilers do not give any error when running the code. But others may give. In order to solve the problem, you must know that Tab key is different from four space in these compilers. So, the error-free code is here:

    try:
        name = input()
     
        if len(name)<4:
            raise NameError 
        else:
            print("Account Created")
    except:
        print("Invalid Name")
    

    To describe more, before "name", if, and else you must put a single tab not four spaces. Also, the statement inside if needs a double Tab to work well.

    I hope other guys take advantage of this question-answer. Please like both the question and answer if it was helpful.

    Best regards, Thank you