这是一个简单的登录程序 - 逻辑在 VB.Net 中工作,但我无法将其转换为 Python。 Python 代码不起作用,但 Stackoverflow 上的两个用户(un_lucky 和 Jerry)提供的 VB.Net 代码可以。有人可以帮我指出 python 代码的修复吗?当密码不正确时,它基本上会产生一系列“访问被拒绝”而不是仅仅一个,并且如果用户名或密码是数组中的第二个,那么它会产生一个访问被拒绝,然后是一个访问授予。
count=0
for counter in range(0,len(fields)):
if textlogin.get()==fields[counter] and textpassword.get()==fields[counter+1]:
count=count+1
if count > 0:
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
这里是 VB.net 代码(逻辑),它确实可以实现几乎相同的功能,只不过上面的 python 程序是从文本文件读取。
现在它可以完美运行(几乎),但是用户名和密码中的空白条目也会生成“已授予访问权限”...无法弄清楚为什么! 完整代码如下:
def verifylogin():
fin=open("moosebook.txt","r")
data=fin.readlines()
for line in data:
fields=line.split()
fields=[i.rstrip("','") for i in fields] #strips the named character from END of field
fields=[i.replace("'",'') for i in fields]#when reading the list, you want to remoe the ',' so it isn't part of the username or password
fields=[i.replace("(",'') for i in fields] #simiarly, remove the bracket and replace it
fields=[i.replace(")",'') for i in fields] #simiarly, remove the bracket and replace it
line=line.rstrip()
print(fields)
flag=0
for counter in range(0,len(fields)):
if textlogin.get()==fields[counter] and textpassword.get()==fields[counter+1]:
flag=flag+1
if flag>0:
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
最佳答案
缩进在Python中很重要。您将 if
测试放在循环内。您需要删除额外的缩进以将其放置在循环之外:
for counter in range(0,len(fields)):
if textlogin.get()==fields[counter] and textpassword.get()==fields[counter+1]:
count=count+1
if count > 0:
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
请注意 if
和 else
行现在如何与 for
行在同一列开始。
因为在您的代码中,if
语句缩进到更深的级别(与 if
测试检查密码相同),因此您多次创建标签,一次每次运行循环。
缩进用于分隔代码块,就像 VB.NET 代码使用 Next
和 End If
显式分隔循环和条件测试一样。
循环可能可以被清理;仅调用 textlogin.get()
和 textpassword.get()
一次,并使用 zip()
配对字段值,以及any()
查看是否有第一个匹配项(这里就足够了):
login, pw = textlogin.get(), textpassword.get()
if any(pair == (login, pw) for pair in zip(fields, fields[1:])):
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
如果您打算将字段作为对(而不是作为滑动窗口)循环,则使用:
login, pw = textlogin.get(), textpassword.get()
fields_iter = iter(fields)
if any(pair == (login, pw) for pair in zip(fields_iter, fields_iter)):
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
关于Python - for 循环内的 if 和 else 且 count 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32355172/