为什么这个循环没有检测到正确的变量名称正常工作?

时间:2018-05-14 04:14:38

标签: python python-3.x

# Variables names must start with a letter or an underscore.
condition = False
#Lets check whether the first character is either a letter or an underscore.
if name[0].isalpha():
    condition = True
elif name[0] == '_':
    condition = True
else:
    condition = False
    pass

# Set condition to False just so it's more readable for me.
#Lets check the rest of the elements starting after 1 to see whether 
#they don't contain a non-letter, number or 
#underscore
for e in name[1:]:
    if e.isnumeric() or e.isalpha() or e == '_':
        condition = True
    else:
        condition = False
return condition

所以基本上它返回True或False,无论提供的变量名是否有效。有人能给我一个暗示我做错的事吗?

1 个答案:

答案 0 :(得分:1)

您的问题在循环for e in name[1:]:内。每次循环播放时,您都会将condition设置为TrueFalse,无论原始值是什么。您可能希望在condition变为假时立即退出循环。