Python- checking for letters, numbers, and underscore character.
Question: I have to write a program that checks if a user's variable name is valid.
These are the rules I am checking for: Only letters, numbers, and the
underscore character are allowed. The first character cannot be a number.

I am not sure what I am doing wrong. Every time I run the program, it tells me
that it's a valid variable, even for invalid inputs.

Here is my program:

    
    
    import string
    
    def valid(name):
        for character in (name):
            if name[0].isdigit():
                name==False
                break 
            else:
                if character.isalnum() and character is ('_'):
                    name==True
                else:
                    name==False
        return
    
    def main():
        name=input("Enter your Python variable name: ")
    
        while name != "done":
            valid(name)
    
            if True:
                print("This is a valid variable name.")
    
            else:
                print("This is not a valid variable name.")
    
            name=input("Enter your Python variable name or 'done': ")
    
    main()
    

Here is a sample output (if done right):

    
    
    Enter your Python variable name: high_temp
    This is a valid variable name.
    
    Enter your Python variable name or "done": highTemp2
    This is a valid variable name.
    
    Enter your Python variable name or "done": 2_high_temp
    This is not a valid variable name.
    
    Enter your Python variable name or "done": done
    

Thank you in advance!


Answer: I'd write it this way:

    
    
    def valid(name):
        return not name[0].isdigit() and all(c.isalnum() or c == '_' for c in name)
    

But perhaps this would make more sense now:

    
    
    def valid(name):
        if name[0].isdigit():
           return False
        for c in name:
           if not (c.isalnum() or c == '_'):
              return False
        return True
    
    def main():
    
        while True:
    
            name = input("Enter your Python variable name or 'done': ")
    
            if name == "done":
               break
    
            if valid(name):
                print("This is a valid variable name.")
            else:
                print("This is not a valid variable name.")
    
    main()
    

