简体   繁体   中英

Lists/Dictionaries from function not returned

I'm trying to write a script in Python using BioPython that reads a FASTA file and generates a list of the raw DNA sequences as entries.

As this code will be used by many other scripts I will be writing, I want the function for this purpose to be in a separate Python file, which I can import at the start of every other script I write. The script containing the function I am currently calling is as so:

from Bio import SeqIO
def read_fasta(dna):
    genome = []
    for seq_record in SeqIO.parse(dna, "fasta"):
        genome.append(str(seq_record.seq))
    return genome

When I call this function in Python from cmd, the function works and reads the files generating the list as I wish. However, if I try to access the list genome again, I get an Traceback | NameError: name 'genome' not defined Traceback | NameError: name 'genome' not defined error.

Can somebody explain why this is happening, even thought I have put the return genome statement? And what I can do to fix this problem?

genome is in the local scope of the function, so it is not visible from the "outside". You should assign result of read_fasta function to some variable in order to access the returned result of the function. For example:

new_variable = read_fasta("pcr_template.fasta")

And it is read - let the new_variable be assigned to the result of the function read_fasta with "pcr_template.fasta" as argument.

Now the genome (or anything that your function has returned) is accessed simply by accessing new_variable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM