I'm taking an online Python course and in one of the lectures, we wrote a program that reads dna sequences from a file and puts them into a dictionary. The file being read has the following form
>header1
dna sequence 1
>header2
dna sequence 2
>header3
dna sequence 3
...
An example file would be
>seq1
aaacgtgtgccccgatagttgtgtcagt
>seq2
acccgtgcacacagtgccaaggggatat
atagatatc
>seq3
agctcgatcgatcgattttagcgagagg
gagagacttcgatcgatcgagtcgatcg
a
Here's the program:
try:
f = open("fasta.txt")
except IOError:
print("Coulnd't open file")
seqs = {}
for line in f:
line = line.rstrip()
if (line[0] == ">"):
words = line.split()
name = words[0][1:]
seqs[name] = ''
else:
seqs[name] = seqs[name] + line
f.close()
print(seqs['seq5'])
My question is, why does this program work? From what I know about programming languages, variables have a scope in the block in which they are defined. In the program, the variable name
, is defined in the "if" part of the program, but then it's referenced in the "else" part of the program. But the only way that a program is going to enter the "else" part of the program is if it doesn't enter the "if" part, so it won't encounter the variable name
. So in my mind, this program shouldn't be working. But it does for some reason.
So I wanted to ask, why it's working. How do variable scopes work in Python?