Reputation: 118
I'm coding Python and I have this problem that I searched for throughout this website and others and I still can't find an actual answer for this problem I am facing. The best way to ask this is by showing the code first:
def showFile():
with open("Password.txt","r") as file:
userShowType = input("What password do you want to show? \n")
for line in file:
if userShowType in line:
print (line)
What I want the program to do is for the user to enter the type of password (e.g. Outlook, Gmail, Youtube, etc) and the computer to search for it. If the computer finds the word, it will print the entire line that contains both the type of password and password. If it doesn't, then the computer will print a line telling the user that the type of password doesn't exist or that the comptuer couldn't find it.
However, the above code does not perform the latter of the if statement, only the former and prints out if the computer found the password. Is there any way in which I can do both?
Upvotes: 0
Views: 58
Reputation: 1029
Since the default answer is a message stating the password wasn't found, by pre-seeding such message & only updating it if the test criteria is met will produce the desired outcome
def showFile():
with open("Password.txt","r") as file:
userShowType = input("What password do you want to show? \n")
msg = 'passwd not present in file'
for line in file:
if userShowType in line:
msg = line
break
print(msg)
The for loop over lines will only update msg if the requested password is found (and equally break out of the loop). The the final print will display the message
Upvotes: 1