简体   繁体   English

只获取一次循环返回的值到 print()

[英]Getting the Value returned from a Loop to print() only once

When trying to retrieve the decrypted password for the second choice, I can't keep the program from printing Does Not Compute no matter whether the website entered is true or not.在尝试检索第二选择的解密密码时,无论输入的网站是否正确,我都无法阻止程序打印Does Not Compute It prints twice when it is untrue so this leads me to believe the it's printing for i in the range(len(passwords)) which is 2.当它不正确时它会打印两次,所以这让我相信它for i in the range(len(passwords))打印for i in the range(len(passwords)) ,即 2。

How do I get it to print just the password or Does Not Compute once and not have it iterate again?我如何让它只打印密码或Does Not Compute一次而不让它再次迭代? I'm trying to check if the input is equal to the website but it still prints iterates twice.我试图检查输入是否等于网站,但它仍然打印迭代两次。

import csv
import sys

# The password list - We start with it populated for testing purposes
passwords = [["yahoo", "XqffoZeo"], ["google", "CoIushujSetu"]]
# The password file name to store the passwords to
passwordFileName = "samplePasswordFile"
# The encryption key for the caesar cypher
encryptionKey = 16
# Caesar Cypher Encryption
def passwordEncrypt(unencryptedMessage, key):
    # We will start with an empty string as our encryptedMessage
    encryptedMessage = ""
    # For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage
    for symbol in unencryptedMessage:
        if symbol.isalpha():
            num = ord(symbol)
            num += key
            if symbol.isupper():
                if num > ord("Z"):
                    num -= 26
                elif num < ord("A"):
                    num += 26
            elif symbol.islower():
                if num > ord("z"):
                    num -= 26
                elif num < ord("a"):
                    num += 26
            encryptedMessage += chr(num)
        else:
            encryptedMessage += symbol
    return encryptedMessage


def loadPasswordFile(fileName):
    with open(fileName, newline="") as csvfile:
        passwordreader = csv.reader(csvfile)
        passwordList = list(passwordreader)
    return passwordList


def savePasswordFile(passwordList, fileName):
    with open(fileName, "w+", newline="") as csvfile:
        passwordwriter = csv.writer(csvfile)
        passwordwriter.writerows(passwordList)


prompt_msg = """
What would you like to do:
 1. Open password file
 2. Lookup a password
 3. Add a password
 4. Save password file
 5. Print the encrypted password list (for testing)
 6. Quit program
Please enter a number (1-4)
"""

while True:
    print(prompt_msg)
    choice = input()

    if choice == "1":  # Load the password list from a file
        passwords = loadPasswordFile(passwordFileName)

    elif choice == "2":  # Lookup at password
        print("Which website do you want to lookup the password for?")
        for keyvalue in passwords:
            print(keyvalue[0])
        print("----")
        passwordToLookup = input()
        for i in range(len(passwords)):
            print(f"i={i}, store_info={passwords[i]}, website={passwords[i][0]}")
            if passwordToLookup == passwords[i][0]:
                password = passwordEncrypt(passwords[i][1], -(encryptionKey))
                print(f"=> The password is {password}.")
            else:
                print("=> Does not compute!")

    elif choice == "3":
        print("What website is this password for?")
        website = input()
        print("What is the password?")
        unencryptedPassword = input()
        unencryptedPassword = passwordEncrypt(unencryptedPassword, encryptionKey)
        newList = [website, unencryptedPassword]
        passwords.append(newList)
        print("Your password has been saved.")

    elif choice == "4":  # Save the passwords to a file
        savePasswordFile(passwords, passwordFileName)

    elif choice == "5":  # print out the password list
        for keyvalue in passwords:
            print(", ".join(keyvalue))

    elif choice == "6":  # quit our program
        sys.exit()

    print()
    print()
    ####### YOUR CODE HERE ######
    # You will need to find the password that matches the website
    # You will then need to decrypt the password
    #
    # 1. Create a loop that goes through each item in the password list
    #  You can consult the reading on lists in Week 5 for ways to loop through a list
    #
    # 2. Check if the name is found.  To index a list of lists you use 2 square backet sets
    #   So passwords[0][1] would mean for the first item in the list get it's 2nd item (remember, lists start at 0)
    #   So this would be 'XqffoZeo' in the password list given what is predefined at the top of the page.
    #   If you created a loop using the syntax described in step 1, then i is your 'iterator' in the list so you
    #   will want to use i in your first set of brackets.
    #
    # 3. If the name is found then decrypt it.  Decrypting is that exact reverse operation from encrypting.  Take a look at the
    # caesar cypher lecture as a reference.  You do not need to write your own decryption function, you can reuse passwordEncrypt
    #
    #  Write the above one step at a time.  By this I mean, write step 1...  but in your loop print out every item in the list
    #  for testing purposes.  Then write step 2, and print out the password but not decrypted.  Then write step 3.  This way
    #  you can test easily along the way.
    #

It seems like you want to print does not compute only if NONE of the stored passwords match the input;好像你要打印does not compute仅当存储的密码都没有输入匹配; but as it is, you're printing that message for EACH password that doesn't match (even if some other password did match).但实际上,您正在为不匹配的每个密码打印该消息(即使其他密码确实匹配)。

I've modified your loop to break when a match is found, and only print the message if no matches were found (by adding an else clause to the for loop, which executes only if the loop makes it all the way to the end.)我已经修改了您的循环以在找到匹配项时中断,并且仅在未找到匹配项时才打印消息(通过在 for 循环中添加一个else子句,只有当循环一直运行到最后时才会执行该子句。 )

    passwordToLookup = input()
    for i in range(len(passwords)):
        if passwordToLookup == passwords[i][0]:
            webSite = passwordEncrypt(passwords[i][1],-(encryptionKey))
            print()
            print('The password is ' + webSite+'.')
            print(i)
            print(passwords[i])
            print(passwords[i][0])
            break
    else:
        # if we got to the end of the loop, no passwords matched
        print('Does not compute!')

First, I took the liberty to reformat and improve your code to look a bit nicer.首先,我冒昧地重新格式化并改进您的代码,使其看起来更好看。

  • Multi-line string for the prompt提示的多行字符串
  • F-string to print variables (Python 3.4 and above)用于打印变量的 F 字符串(Python 3.4 及更高版本)
  • Formatting with the new black module使用新的black模块格式化

Your problem is that you loop through all the stored websites您的问题是您遍历所有存储的网站

    for i in range(len(passwords)):
        if passwordToLookup == passwords[i][0]:
            ...
        else:
            ...

Actually what you should do is其实你应该做的是

  1. Checking if the website exists in the current list检查当前列表中是否存在该网站
  2. Return decrypted password if found, and Cannot computer otherwise如果找到则返回解密的密码,否则Cannot computer

The best way to do 1. is to: 1. 最好的方法是:

  • Transform the tuples of passwords to a dictionary: passwords = {"yahoo":"XqffoZeo", "google":"CoIushujSetu"}将密码元组转换为字典: passwords = {"yahoo":"XqffoZeo", "google":"CoIushujSetu"}
  • Check if website is one of the keys: if website in passwords.keys(): ...检查网站是否是关键之一: if website in passwords.keys(): ...
  • Update the rest of the code accordingly (as the list of passwords is not a list of tuples but a dictionary)相应地更新其余代码(因为密码列表不是元组列表而是字典)

Or more simply: just transform the list of tuples to a dictionary when extracting the password:或者更简单:在提取密码时只需将元组列表转换为字典:

elif choice == "2":  # Lookup at password
    print("Which website do you want to lookup the password for?")
    for keyvalue in passwords:
        print(keyvalue[0])
    print("----")
    passwordToLookup = input()
    dict_passwords = dict(passwords)
    if passwordToLookup in dict_passwords:
        encrypted = dict_passwords[passwordToLookup]
        password = passwordEncrypt(encrypted, -(encryptionKey))
        print(f"=> The password is {password}.")
    else:
        print("=> Does not compute!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM