我必须编写一个程序来检查用户的变量名是否有效。这些是我要检查的规则:只允许使用字母,数字和下划线字符。第一个字符不能是数字。
我不确定我做错了什么。每次运行程序时,它都会告诉我它是一个有效变量,即使对于无效输入也是如此。
这是我的计划:
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()
这是一个示例输出(如果正确完成):
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
提前谢谢!
答案 0 :(得分:3)
我这样写:
def valid(name):
return not name[0].isdigit() and all(c.isalnum() or c == '_' for c in name)
但也许这会更有意义:
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()
答案 1 :(得分:1)
另一种pythonic解决方案,
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)
答案 2 :(得分:0)
if True
总是True
。你的意思是说
if valid(name)
您只需要拨打valid
答案 3 :(得分:0)
您似乎可以使用isidentifier
方法
return name.isidentifier()