Python 仅获取一次从循环返回到print()的值
当尝试检索第二个选项的解密密码时,我无法阻止程序打印Python 仅获取一次从循环返回到print()的值,python,python-3.x,loops,iteration,string-length,Python,Python 3.x,Loops,Iteration,String Length,当尝试检索第二个选项的解密密码时,我无法阻止程序打印不计算,无论输入的网站是否为真。当它不真实时,它会打印两次,因此这让我相信它正在为范围(len(passwords))内的i打印,,该范围为2 我如何让它只打印密码,或者不计算一次,而不让它再次迭代?我试图检查输入是否等于网站,但它仍然会重复打印两次 import csv import sys # The password list - We start with it populated for testing purposes passw
不计算
,无论输入的网站是否为真。当它不真实时,它会打印两次,因此这让我相信它正在为范围(len(passwords))内的i打印,
,该范围为2
我如何让它只打印密码,或者不计算一次
,而不让它再次迭代?我试图检查输入是否等于网站,但它仍然会重复打印两次
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.
#
导入csv
导入系统
#密码列表-我们从为测试目的填充它开始
密码=[[“雅虎”、“XqffoZeo”]、[“谷歌”、“CoIushujSetu”]]
#用于存储密码的密码文件名
passwordFileName=“samplePasswordFile”
#凯撒密码的加密密钥
encryptionKey=16
#凯撒密码
def passwordEncrypt(未加密的消息,密钥):
#我们将以一个空字符串作为加密消息开始
encryptedMessage=“”
#对于未加密消息中的每个符号,我们将在加密消息中添加一个加密符号
对于未加密消息中的符号:
如果symbol.isalpha():
num=ord(符号)
num+=键
如果symbol.isupper():
如果num>ord(“Z”):
num-=26
以利夫数:
num+=26
elif symbol.islower():
如果num>ord(“z”):
num-=26
以利夫数:
num+=26
encryptedMessage+=chr(num)
其他:
encryptedMessage+=符号
返回加密消息
def loadPasswordFile(文件名):
将open(fileName,newline=“”)作为csvfile:
passwordreader=csv.reader(csvfile)
passwordList=列表(passwordreader)
返回密码列表
def savePasswordFile(密码列表,文件名):
打开(文件名为“w+”,换行为“”)作为csvfile:
passwordwriter=csv.writer(csvfile)
passwordwriter.writerows(密码列表)
提示“msg=”“”
您想做什么:
1.打开密码文件
2.查找密码
3.添加密码
4.保存密码文件
5.打印加密密码列表(用于测试)
6.退出计划
请输入一个数字(1-4)
"""
尽管如此:
打印(提示信息)
选择=输入()
如果选项==“1”:#从文件加载密码列表
密码=加载密码文件(密码文件名)
elif choice==“2”:#在密码处查找
打印(“要查找哪个网站的密码?”)
对于密码中的keyvalue:
打印(键值[0])
打印(“---”)
passwordToLookup=input()
对于范围内的i(len(密码)):
打印(f“i={i},存储信息={passwords[i]},网站={passwords[i][0]}”)
如果passwordToLookup==密码[i][0]:
password=passwordEncrypt(密码[i][1],-(encryptionKey))
打印(f“=>密码为{password}。”)
其他:
打印(“=>不计算!”)
elif选项==“3”:
打印(“此密码用于哪个网站?”)
网站=输入()
打印(“密码是什么?”)
未加密密码=输入()
unencryptedPassword=passwordEncrypt(unencryptedPassword,encryptionKey)
newList=[网站,未加密密码]
密码。追加(新列表)
打印(“您的密码已保存。”)
elif choice==“4”:#将密码保存到文件中
savePasswordFile(密码、密码文件名)
elif choice==“5”:#打印出密码列表
对于密码中的keyvalue:
打印(“,”.join(keyvalue))
elif choice==“6”:#退出我们的计划
sys.exit()
打印()
打印()
#######你的代码在这里######
#您需要找到与网站匹配的密码
#然后需要解密密码
#
# 1. 创建一个循环,遍历密码列表中的每个项目
#你可以参考第5周的列表阅读,了解循环浏览列表的方法
#
# 2. 检查是否找到该名称。要索引列表列表,请使用2个方形背景集
#因此,密码[0][1]意味着列表中的第一项将获得第二项(请记住,列表从0开始)
#因此,根据页面顶部预定义的内容,这将是密码列表中的“XqffoZeo”。
#如果您使用步骤1中描述的语法创建了一个循环,那么我是列表中的“迭代器”,因此
#我想在第一组括号中使用i。
#
# 3. 如果找到该名称,则对其进行解密。解密是与加密完全相反的操作。看一看
#凯撒·塞弗的演讲作为参考。您不需要编写自己的解密函数,您可以重用passwordEncrypt
#
#一次写一个步骤。我是说,写第一步。。。但在你的循环中,打印出列表中的每一项
#用于测试目的。然后编写步骤2,打印出密码,但不解密。然后写第3步。这边
#你可以很容易地进行测试。
#
似乎只有在存储的密码与输入不匹配的情况下,才希望打印不计算
;但实际上,您正在为每个不匹配的密码打印该消息(即使其他密码确实匹配)
我已将您的循环修改为在找到匹配项时中断,并且仅在未找到匹配项时打印消息(通过向for循环添加else
子句,该子句仅在循环一直执行到结束时执行)
首先,我冒昧地重新格式化并改进了您的代码,使其看起来更好
- 提示的多行字符串
- 打印变量的F字符串(Python 3.4及更高版本)
- 使用新的
模块格式化黑色
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!')
for i in range(len(passwords)): if passwordToLookup == passwords[i][0]: ... else: ...
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!")