我做错了什么,python循环不重复?

时间:2016-10-13 22:43:55

标签: python

我刚刚有这个工作,现在,对于我的生活,我无法继续循环,因为它只产生第一个输入的结果。我哪里做错了?我知道我是业余爱好者,但无论你有什么帮助都会很棒!谢谢。

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()

1 个答案:

答案 0 :(得分:2)

这是一个范围问题。默认情况下,Python变量在范围内是本地的。在servy中,你将inez设置为一个新值,Python认为这是一个新的局部变量,因为你没有特别声明它是全局的。因此,当您第二次调用serx时,全局变量inez保持不变。这是一个更简单的例子来说明这个问题。

a = "hello"

def b():
    print(a)

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

b()
c()

这是一个让我多次绊倒的令人讨厌的错误。如果可能的话,避免全局变量的一个重要原因。

上述代码还存在其他问题,例如使用可能使用循环的递归。我建议阅读有关python的范围规则(Short Description of the Scoping Rules?),尝试重组以避免递归,然后在http://codereview.stackexchange.com上发布代码。

相关问题