首页 > 解决方案 > 如何循环我的密码/用户名登录页面并从外部文件中读取密码/用户名?

问题描述

我知道关于如何循环和读取文本文件的多个帖子和来源。我很抱歉成为那个人,但我最近是 Python 的新手,我在凌晨 1:00 写这篇文章。

正如标题所示,我如何循环我的登录页面,以便如果用户输入的详细信息不正确,那么他们将有机会再次尝试,直到他们正确输入了详细信息。密码/用户名也需要从外部文件中读取。

我的代码:

print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
    userInput = input("Password?\n")   
    if userInput == password:
       print("Welcome!")
       print('\n--------------------------------------------------------\n')
       print ("BTN = 0.10")
       print ("= £315.37")
    else:
       print("That is the wrong password.")
else:
    print("That is the wrong username.")
print('\n--------------------------------------------------------\n')

标签: python

解决方案


做这样的事情:

password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
    print("incorrect")
    theirUsername = input("What is your username")
    theirPassword = input("What is your password")
print("correct")



file = open("externalfile.txt","r")您可以使用then 读取外部文件,text = file.read()如果文件格式为

username
password

text = text.split("\n")然后username = text[0]password = text[1]

这就是它应该看起来像一个解释:

file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
    print("incorrect") #notifies them of being wrong
    theirUsername = input("What is your username") #gets new username input
    theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct

推荐阅读