下面的代码是我一直在从事的一个夏季项目:

from time import sleep

def valrep(x,change): #function goes through a file and replaces specific values
    with open('users.txt', 'r') as file :
        filedata = file.read()
    for aline in open("users.txt","r").readlines():
        word = aline.split()
        if (word[0] == username) and (word[1] == user_password):
            aline2 = aline.replace(word[x], change)
            filedata = filedata.replace(aline,aline2)
    with open('users.txt', 'w') as file:
        file.write(filedata)
        print("SUCCESS")

loop = False
while loop == False:
    username = input("ENTER A VALID USERNAME>>> ")#splits the input into two seperate variables
    user_password = input("ENTER A VALID 4 DIGIT PIN>>> ")
    valnums = '1234567890' #gives a set of valid characters (used later in the program)
    with open("users.txt","r") as user_file:
        for aline in user_file.readlines():
            vals = aline.split()
            if (vals[0] == username) and (vals[1] == user_password):#goes through the text file looking for the valid username and password
                loop2 = False
                while loop2 == False:
                    sleep(3.0) #delays the time for menu to appear
                    print("\n"*300,"="*30,"\n\n\nWELCOME TO HAYDON BANK, {} \n\n\n".format(username),"="*30,"\n  WHICH SERVICE DO YOU REQUIRE?\n","="*30,"\n\n\n    Option 1: View Balance\n\n    Option 2: Withdrawal\n\n    Option 3: Change PIN\n\n\n","="*30,"\n")#this is the menu
                    balance = vals[2] #sets respective part of the file as the balance variable
                    print("\n"*6)
                    option = input("INPUT OPTION PRESS 'Q' TO QUIT>>> ")
                    if option == '1':
                        print("£",balance)
                        sleep(2.0)
                    elif option == '2':
                        withdrawal = input("SELECT AMOUNT TO WITHDRAW:\n £10\n £20\n £50\n £100\n OR INPUT AN AMOUNT THAT IS DIVISIBLE BY 10\n\n\nINPUT AMOUNT>>> £")
                        if withdrawal%10 == 0:
                            print("You selected:£",withdrawal)
                            newbalance = float(balance) - float(withdrawal)#sets the newbalance variable
                            valrep(2,str(newbalance))
                            print("New Balance:£",newbalance)
                            sleep(2.0)
                    elif option == '3':
                        loop3 = True
                        while loop3 == True:
                            old_pass, new_pass = input("input old PIN and new PIN: ").split(" ")
                            if len(new_pass) != 4: #checks if new_pass is 4 characters long
                                print("INCORRECT LENGTH")
                            elif False in [c in valnums for c in new_pass]: #loops through valnums and compares the variable new_pass to have valid characters   
                                print("INVALID CHARACTERS")
                            elif old_pass == user_password: #checks if old_pass is equal to user_password
                                valrep(1,new_pass)
                                print("New PIN: ",new_pass)
                                loop3 = False
                                sleep(2.0)
                    elif option.lower() == 'q':
                        loop2 = True
                        print("Bye", username)
                        sleep(5.0)
                    else:
                        print("INVALID INPUT")
            else:
                print("INVALID INPUT")
                break

users.txt文件:

user0001 1234 123.45
user0002 1234 123.45
user0003 1234 123.45
...
user9999 1234 123.45

问题是,当我在用户名或user_password变量的文本文件中输入更接近9999行的值时,它给了我以下输出:

"INVALID INPUT"
"INVALID INPUT"
"INVALID INPUT"
...

直到代码在文本文件中找到值为止。

但我希望输出是这样的:

ENTER A VALID USERNAME>>> user9999
ENTER A VALID 4 DIGIT PIN>>> 1234

 ============================== 


WELCOME TO HAYDON BANK, user0001 


 ============================== 
  WHICH SERVICE DO YOU REQUIRE?
 ============================== 


    Option 1: View Balance

    Option 2: Withdrawal

    Option 3: Change PIN


 ============================== 





INPUT OPTION PRESS 'Q' TO QUIT>>> 

我该怎么做呢?

注意:我不是一个真正的程序员,我只是一个了解python编码的大多数基础知识并且没有其他类型的编码的孩子

#1楼 票数:0 已采纳

您所期望的与您的代码不一致。

for aline in user_file.readlines():
    vals = aline.split()
    if (vals[0] == username) and (vals[1] == user_password):
        #...
    else:
        print("INVALID INPUT")
        break

由于您从第一行开始进行匹配,因此,直到找到给定的用户名=“ user9999”的匹配项,匹配才会发生。 每次发生不匹配时,都会打印“无效输入”。

解决此问题的快速方法是使用“ for ... else ...”。 请参阅for ... else ..的参考 (需要break ,以使else知道我们得到了搜索的内容。)

for aline in user_file.readlines():
    vals = aline.split()
    if (vals[0] == username) and (vals[1] == user_password):
        #Process...
        break #let the "else" in next line knowing "we have found"
else:
    print("INVALID INPUT")
    break

在上面的代码中, else语句仅在没有找到匹配项的情况下执行。 希望这就是你想要的。

-----------------------------------------

可运行代码根据您发布的内容进行了更改。

from time import sleep
def valrep(x,change): #function goes through a file and replaces specific values
    with open('users.txt', 'r') as file :
        filedata = file.read()
    for aline in open("users.txt","r").readlines():
        word = aline.split()
        if (word[0] == username) and (word[1] == user_password):
            aline2 = aline.replace(word[x], change)
            filedata = filedata.replace(aline,aline2)
    with open('users.txt', 'w') as file:
        file.write(filedata)
        print("SUCCESS")

loop = False
while loop == False:
    username = input("ENTER A VALID USERNAME>>> ")#splits the input into two seperate variables
    user_password = input("ENTER A VALID 4 DIGIT PIN>>> ")
    valnums = '1234567890' #gives a set of valid characters (used later in the program)
    with open("users.txt","r") as user_file:
        for aline in user_file.readlines():
            vals = aline.split()
            if (vals[0] == username) and (vals[1] == user_password):#goes through the text file looking for the valid username and password
                loop2 = False
                while loop2 == False:
                    sleep(3.0) #delays the time for menu to appear
                    print("\n"*3,"="*30,"\n\n\nWELCOME TO HAYDON BANK, {} \n\n\n".format(username),"="*30,"\n  WHICH SERVICE DO YOU REQUIRE?\n","="*30,"\n\n\n    Option 1: View Balance\n\n    Option 2: Withdrawal\n\n    Option 3: Change PIN\n\n\n","="*30,"\n")#this is the menu
                    balance = vals[2] #sets respective part of the file as the balance variable
                    print("\n"*6)
                    option = input("INPUT OPTION PRESS 'Q' TO QUIT>>> ")
                    if option == '1':
                        print("£",balance)
                        sleep(2.0)
                    elif option == '2':
                        withdrawal = input("SElECT AMOUNT TO WITHDRAW:\n £10\n £20\n £50\n £100\n OR INPUT AN AMOUNT THAT IS DIVISIBLE BY 10\n\n\nINPUT AMOUNT>>> £")
                        if withdrawal%10 == 0:
                            print("You selected:£",withdrawal)
                            newbalance = float(balance) - float(withdrawal)#sets the newbalance variable
                            valrep(2,str(newbalance))
                            print("New Balance:£",newbalance)
                            sleep(2.0)
                    elif option == '3':
                        loop3 = True
                        while loop3 == True:
                            old_pass, new_pass = input("input old PIN and new PIN: ").split(" ")
                            if len(new_pass) != 4: #checks if new_pass is 4 characters long
                                print("INCORRECT LENGTH")
                            elif False in [c in valnums for c in new_pass]: #loops through valnums and compares the variable new_pass to have valid characters
                                print("INVALID CHARACTERS")
                            elif old_pass == user_password: #checks if old_pass is equal to user_password
                                valrep(1,new_pass)
                                print("New PIN: ",new_pass)
                                loop3 = False
                                sleep(2.0)
                    elif option.lower() == 'q':
                        loop2 = True
                        print("Bye", username)
                        sleep(5.0)
                    else:
                        print("INVALID INPUT")
                break  # this break is needed to let the "else" in next line knowing "we have found what we want"
        else:
            print("INVALID INPUT!!")
            continue #comment this if you allow multi-user or re-login

  ask by bleh translate from so

未解决问题?本站智能推荐:

3回复

在文本文件中找到行

您将实现函数index(),该函数将文本文件的名称和单词列表作为输入。 对于列表中的每个单词,您的函数都将在文本文件中找到单词所在的行,并打印相应的行号(编号从1开始)。 您应该只打开和读取一次文件。 我只能计数一次。
1回复

如何在Python中将(if-else)打印语句的输出重定向到文本文件

我有这段代码,然后将输出打印到txt文件中。 但是,每当我打开文件f = open(“ out.txt”,'w')时,它都会显示意外的缩进。 我想我将代码行放置在错误的位置。 谁能帮忙。
2回复

Python:在文本文件中找到最大x值和最大y值

我有关于在文本文件中找到最大x或y值的问题。 这对于多边形算法中的点是必要的。 多边形与点,输入或输出多边形以及多边形的行数一起输入到文本文件中。 例如: 点是[5.0 4.0] ,多边形有6行,接下来是多边形的写点: 首先是x坐标,第二个是y坐标。 我有测试2
2回复

在文本文件的一列中找到局部最大值

我有一个包含两行的文本文件。 我想找到第一行的局部最大值。 我正在尝试下面的代码,但我不知道为什么会收到此错误:“ x必须是一维数组” 输入是这样的: 输出应为:
2回复

如何在文本文件中找到某个单词

我有一个文件文本,我想用条件过滤文本中的一些单词: 1)长度相同且以相同字母开头 2)查找带有至少2个正确放置的字母的单词 例如: 词=鼓 文本 并希望输出: ['bulks', 'bible']与bulks有“B”和“U”正确地放置和bible有2 b正确
3回复

如何“突出显示”在文本文件中找到的单词?

我正在一个文本文件中搜索一个词。 它找到单词并返回包含该单词的行。 这很好,但我想在该行中突出显示或加粗。 我可以在 Python 中做到这一点吗? 我也可以使用更好的方法来获取用户的 txt 文件路径。
3回复

我想在文本文件中找到每个单词的长度

我试图在我的文本文件中单独找到单词的长度。 我通过以下代码进行了尝试,但此代码向我显示了该单词在文件中使用的次数。 输出是这样的 china : 14 emerged : 1 as : 16 one : 5 of : 44 the : 108 world's : 7 first : 2 civi
2回复

在文本文件python中找到行索引

我想在文本文件(内容)中获取与某个字符串(在这种情况下,InChI = 1S / C11etc ..)相对应的行的索引,这是我的代码: 但是我得到空括号[]。 但是我很确定该行存在,因为如果运行此命令: 我得到我感兴趣的电话。