如何在文本文件中找到值之前停止else语句的循环输出?

时间:2017-08-16 00:54:47

标签: python

以下代码是我一直致力于的夏季项目:

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 :(得分: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 ..."。请参阅a reference of for ... else ..break需要elsefor 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 语句,找不到匹配项。希望这是你想要的。

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

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

public static List<String> getImageIds(int size) {
    Call<PhotosList> call = flickrService.getPhotos(apiKey, format, "1");
    photoIds = new ArrayList<String>();

    PhotosList photosList = call.execute().body();
    List<Photo> photos = photosList.getPhotos().getPhoto();

    for(Photo photo : photos) {
        Log.d("TEMP_TAG", "adding photo id to list: " + photo.getId());
        photoIds.add(photo.getId());
    }
    Log.d("TEMP_TAG", "it's getting here too");
    return photoIds;
}