[英]My code prints “Not Found” for every line, how do i get it to only print “Not Found” once if the search is unsuccessful?
該程序需要是一個包含姓名、電話號碼和電子郵件的簡單通訊錄。 您需要能夠搜索人員並添加聯系人。 我讓程序以足夠體面的方式保存到文本文件中,並嘗試逐行搜索文件。 如果它具有搜索的名稱,我可以讓它打印該行,但我不知道如何讓程序判斷是否根本找不到聯系人。 使用我的代碼的當前方式,它會為名稱不在的每一行顯示“未找到聯系人”。如果名稱不在文本文件中,我將如何讓它只說一次找不到?
我試過的是:
f = open('contacts.txt', 'a')
def make_contact(name, phone, email):
f = open('contacts.txt', 'a')
f.write('\n' + 'Name: ' + name + ' Phone: ' + phone + ' Email: ' + email)
f.close()
menu_input = 0
while menu_input != 3:
print('\n1. Search Contact\n2. Add Contact\n3. Exit')
menu_input = int(input("\nChoose Option: "))
if menu_input == 1:
name = input ('\nEnter a Name to Search: ')
with open('contacts.txt', 'r') as searchfile:
for line in searchfile:
if name in line:
print("\n" + line)
else:
print("\nContact Not Found!")
f.close()
elif menu_input == 2:
f = open('contacts.txt', 'a')
name = input("Enter Name: ")
phone = input("Enter Phone Number: ")
email = input("Enter Email: ")
make_contact(name, phone, email)
生病添加一個新的聯系人說蒂米,當我搜索蒂米時,它會為每一行顯示“未找到”,直到它到達蒂米。 對於 Timmys 聯系熱線之前的盡可能多的聯系,它會重復“未找到”
使用for-else
更改這部分代碼。
with open('contacts.txt', 'r') as searchfile:
for line in searchfile:
if name in line:
print("\n" + line)
break
else:
print("\nContact Not Found!")
它將通過for
循環檢查if
,當有匹配時,它將打印該行並從循環中中斷。 如果迭代結束並且沒有找到匹配項,它將檢查與for
循環並行的else
條件。
如果您想打印所有重復記錄,請維護一個匹配標志
flag = False
with open('contacts.txt', 'r') as searchfile:
for line in searchfile:
if name in line:
print("\n" + line)
flag = True
if not flag:
print("\nContact Not Found!")
您可以在代碼中添加一個簡單的標志來確定它是否找到。 實現將是這樣的:
with open('contacts.txt', 'r') as searchfile:
found=False
for line in searchfile:
if name in line:
print("\n" + line)
found = True
if not found:
print("\nContact Not Found!")
您可以在搜索循環中添加標志。 一旦你發現,你也可以打破循環。
f = open('contacts.txt', 'a')
def make_contact(name, phone, email):
f = open('contacts.txt', 'a')
f.write('\n' + 'Name: ' + name + ' Phone: ' + phone + ' Email: ' + email)
f.close()
menu_input = 0
while menu_input != 3:
print('\n1. Search Contact\n2. Add Contact\n3. Exit')
menu_input = int(input("\nChoose Option: "))
if menu_input == 1:
flag = False
name = input ('\nEnter a Name to Search: ')
with open('contacts.txt', 'r') as searchfile:
for line in searchfile:
if name in line:
flag = True # here you add flag
print("\n" + line)
break
if not flag:
print("\nContact Not Found!")
f.close()
elif menu_input == 2:
f = open('contacts.txt', 'a')
name = input("Enter Name: ")
phone = input("Enter Phone Number: ")
email = input("Enter Email: ")
make_contact(name, phone, email)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.