我目前是python新手。我的代码遇到了一些问题。您可以在下面看到源代码,该程序以提示用户输入其用户ID的提示开头。然后,该程序会将用户输入的用户ID与StudentIDs.txt中存在的用户ID匹配,但似乎运行不正常。
def login_menu():
while True:
user_input_id = (input('Please enter your student ID: '))
with open('StudentIDs.txt', 'r+') as student_ids:
if user_input_id in student_ids.read():
print('You have access to the system')
else:
print('Invalid ID, the ID is not in the database, please try again')
这是StudentIDs.txt中的数据
1904983
1904984
1904985
当我输入1904983时,我将可以访问系统,但是当我输入190或1或9时,我也将可以访问系统,这使程序完全没有逻辑。有人可以给我解释一下我的程序有什么问题吗,或者可以给我帮助?
答案 0 :(得分:0)
尝试使用==代替in 即您的代码应如下所示:
if user_input_id == student_ids.read():
这两个语句之间的区别在于,当您使用 in 运算符时,它将检查user_input是否存在于student_id中(即使其中一个值将输出True)也是如此。 。另一方面, == 查找值之间的精确匹配。
答案 1 :(得分:0)
if user_input_id in student_ids.read():
在这里,当您使用“ user_input_id in”时,它将检查user_input_id中的内容是否与student_ids中的任何部分匹配。它不是与整个行进行比较,在您的情况下是整个用户ID。因此,如果您先读取文件并将所有ID放在列表中,遍历列表并使用“ ==”进行比较,或者遍历文件中的每一行并使用“ ==”进行比较,那么它将起作用。
user_input_id = (input('Please enter your student ID: '))
with open('StudentIDs.txt') as fp:
while True:
line = fp.readline()
if line:
if user_input_id == line.strip():
print('You have access to the system')
else:
print('Invalid ID, the ID is not in the database, please try again')
else:
break
答案 2 :(得分:0)
您在这里:
{tgg:"egg",ggg:{dfgf:"tyt"}, ff:[{tyuyy:"sd f"}]}
诀窍是def login_menu():
user_input_id = (input('Please enter your student ID: '))
with open('file.txt') as student_ids:
ids = [line.strip("\n") for line in student_ids]
if str(user_input_id) in ids:
print('You have access to the system')
else:
print('Invalid ID, the ID is not in the database, please try again')
login_menu()
,它将所有行都用“ \ n”(新行)分割,然后将它们放到名为id的数组中。
然后:
[line.strip("\n") for line in student_ids]
它只是检查您是否在数组中得到了输入。
注意:不要忘记转换为字符串!