4

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!

john smith
  • 91
  • 3
  • 10
  • What about keywords, like `if`, `for`, `try`, `except`? If you're working with Python 3.x check out [`std.isidentifier()`](https://docs.python.org/3/library/stdtypes.html#str.isidentifier). Also have a look at this question: http://stackoverflow.com/q/12700893/1025391 – moooeeeep Nov 08 '15 at 19:44
  • You can use a regex: `def valid(name): return re.match(r'[a-zA-Z_]\w+', name)` – dawg Nov 08 '15 at 20:05

4 Answers4

3

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()
Dan D.
  • 73,243
  • 15
  • 104
  • 123
2

Looks like you can get away with isidentifier method

return name.isidentifier()
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
Jay
  • 21
  • 1
1

Another pythonic solution,

import string

def valid(name):
   if name[0].isdigit():
       return false
   accepted_chars=string.digits + string.ascii_lowercase + '_'
   return all(item for name if item.lower() in accepted_chars)
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
0
if True

is always True. You mean to say

if valid(name)

You only need this one call to valid

saulspatz
  • 5,011
  • 5
  • 36
  • 47