5 python
我输入了一个用户名 - “User1” - 但是结果总是显示“User1”是一个不正确的用户名,即使它在外部文本文件中。
import random
print ("Welcome to the Music Quiz!")
username = input("please enter your Username...")
f = open("F:/GCSE/Computer Science/Programming/username.txt","r");
lines = f.readlines()
if username == "lines":
print = input("Please enter your password")
else:
print("That is an incorrect username")
Run Code Online (Sandbox Code Playgroud)
如果用户名 - User1 User2 User3 User4 User5 作为用户名输入,则输出应为“请输入您的密码”
lines = f.readlines()将创建文本文件中每一行的列表。前提是每个用户名位于单独的行上。否则,您不想逐行读取它,而是想读取其他分隔符。
您要做的是检查输入的用户名是否在该列表中。所以你会想要:
if username in lines:
Run Code Online (Sandbox Code Playgroud)
但问题是它需要完全匹配。如果有多余的空格,就会失败。所以你可以做的就是使用.strip()来清除任何空白。
还有另一个大问题:
print = input("Please enter your password")
Run Code Online (Sandbox Code Playgroud)
您正在使用 print 函数来存储输入字符串。当你使用input它时,它会打印出来。然后你真正想要的是将输入存储为某种东西......我称之为password
import random
print ("Welcome to the Music Quiz!")
username = input("please enter your Username... ")
f = open("C:/username.txt","r")
# Creates a list. Each item in the list is a string of each line in your text files. It is stored in the variable lines
lines = f.readlines()
# the strings in your list (called lines), also contains escape charachters and whitespace. So this will create a new list, and for each string in the lines list will strip off white space before and after the string
users = [user.strip() for user in lines ]
# checks to see if the username input is also in the users list
if username in users:
password = input("Please enter your password: ")
else:
print("That is an incorrect username")
Run Code Online (Sandbox Code Playgroud)