2

I just had this working, and now, for the life of me, I cannot get the loop to continue, as it only produces the outcome of the first input. Where did I go wrong? I know im an amateur, but whatever help you might have would be awesome! Thanks.

sequence = open('sequence.txt').read().replace('\n','')
enzymes = {}
fh = open('enzymes.txt')
print('Restriction Enzyme Counter')
inez = input('Enter a Restricting Enzyme: ')
def servx():
    for line in fh:
        (name, site, junk, junk) = line.split()
        enzymes[name] = site 
        if inez in fh:
            xcr = site
            print('Active Bases:', site)
    for line in sequence.split():
        if xcr in line:
            bs = (sequence.count(xcr))
            print('Enzyme', inez, 'appears', bs, 'times in Sequence.')
servx()
def servy():
    fh.seek(0);
    qust = input('Find another Enzyme? [Yes/No]: ')
    if qust == 'Yes':
        inez = input('Enter a Restricting Enzyme: ')
        servx()
        servy()
    elif qust == 'No':
        print('Thanks!')
    elif qust != 'Yes''No':
        print('Error, Unknown Command')
servy()
fh.close()
Joker
  • 21
  • 3

1 Answers1

2

This an issue of scope. By default Python variables are local in scope. In servy, where you set inez to a new value, Python assumes this is a new local variable because you have not specifically declared it to be global. Therefore when you call serx the second time, the global variable inez is unchanged. Here is a simpler example to illustrate the issue.

a = "hello"

def b():
    print(a)

def c():
    a = "world"
    print(a)
    b()

b()
c()

That is a nasty bug that has tripped me up many times. One of the great reasons to avoid global variables if at all possible.

There are other issues with the above code, such as using recursion where a loop should probably be used. I would suggest reading about python's scoping rules (Short Description of the Scoping Rules?), try restructuring to avoid recursion and then posting your code on http://codereview.stackexchange.com.

Community
  • 1
  • 1
intrepidhero
  • 701
  • 7
  • 10