Natalie N.

asked • 11/17/23

keep getting this out come "free variable 'valid_passport' referenced before assignment in enclosing scope" please help out

def valid_passport(pp):

requirements = {"pid", "hgt", "cid", "iyr","byr","eyr","ecl","hcl", "ecl"} # Inputs all required keys into a list

return all(field in pp for field in requirements) or \

all(field in pp for field in requirements -{'ecl'}) # since the eye color is irrelevant, we define that here


def main():

pp_info = input("Enter the name of the file: ")

with open(pp_info, 'r') as file: # opens, reads and assigns the provided file

passports = file.read().split("\n\n") # correctly reads each passport information, acknowledging that each bit of information is separated by 2 blank lines

valid_passports = [pp for pp in passports if valid_passport(pp)]

print(f"There are {len(valid_passports)} valid passports")

with open(valid_passports.txt, 'w') as valid_file: # creates a new file with the intention of adding the information of the valid passports

for valid_passport in valid_passports:

valid_file.write(valid_passport + "\n\n") # inputs all the information of each valid passport, and separates them by 2 blank lines


if __name__ == "__main__":

main()

1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.