For a personal project I am required to use two for loops to extract data from a text file to a list. After that, python needs to read the list and check how many times the variable lower_than_six
("password < 6") or greater_than_ten
("password > 10") comes in the code. But for some reason it's not doing it. The code I wrote:
def main():
lower_than_six = "password < 6"
greater_than_ten = "password > 10"
input_file = "ITWorks_password_log.txt"
f = open(input_file, "r")
counter_pw_too_small = 0
counter_pw_too_large = 0
for line in f.readlines():
attempts_list = line.strip()
print(attempts_list)
for line in attempts_list:
if lower_than_six in line:
counter_pw_too_small += 1
elif greater_than_ten in line:
counter_pw_too_large += 1
print(f"\n Password < 6 occurred {counter_pw_too_small} times")
print(f"\n Password > 10 occurred {counter_pw_too_large} times")
main()
You should just fix your code a little bit. Like this:
def main():
lower_than_six = "password < 6"
greater_than_ten = "password > 10"
input_file = "ITWorks_password_log.txt"
f = open(input_file, "r")
counter_pw_too_small = 0
counter_pw_too_large = 0
attempts_list = []
for line in f.readlines():
attempt = line.strip()
attempts_list.append(attempt)
print(attempt)
for line in attempts_list:
if lower_than_six in line:
counter_pw_too_small += 1
elif greater_than_ten in line:
counter_pw_too_large += 1
print(f"\n Password < 6 occurred {counter_pw_too_small} times")
print(f"\n Password > 10 occurred {counter_pw_too_large} times")
main()
You are defining the attempts_list
as the line every time so at the end it is just the last row of the file.
Instead you need to initiate it and then append lines to it. Then things will work.
By the way I am assuming your indentation is just like this due to copy paste, otherwise you need to fix the indentation so that the function lines are inside the (main()) function.
My test text file:
blablalkdslkfvsdf
sdfglksdfglkpassword < 6dflgkld kfgdfg df
sdfgsd fgdfg sdfghpassword < 6dfghdgf
sdfhgdfghsfdghfgb password < 6 ghs dgfh sdfghdfghdgfdsfgs
sdfg sdfg sdfg sdfghdfghdgfdsfgs
sdfg spassword > 10df
sdfgsdghdfgh
Output:
blablalkdslkfvsdf
sdfglksdfglkpassword < 6dflgkld kfgdfg df
sdfgsd fgdfg sdfghpassword < 6dfghdgf
sdfhgdfghsfdghfgb password < 6 ghs dgfh sdfghdfghdgfdsfgs
sdfg sdfg sdfg sdfghdfghdgfdsfgs
sdfg spassword > 10df
sdfgsdghdfgh
Password < 6 occurred 3 times
Password > 10 occurred 1 times