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

2024-09-30 00:40:34 发布

您现在位置: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()

Tags: ininputiflinesiteprintsequencefh
1条回答
网友
1楼 · 发布于 2024-09-30 00:40:34

这是一个范围问题。默认情况下,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。在

相关问题 更多 >

    热门问题