首页 > 解决方案 > 打破一个forloop

问题描述

我目前正在开发我的第一个网站。一种 DNA 到蛋白质的翻译器。事情是这样的,当您输入密码子(三个字母组)tga、tag 或 taa 时。forloop 应该停止。基本上,我想停止 forloop 这是代码:

class TranslatorView(View):
    template_name = 'main/translated.html'

    
    def translate_amino(self, codon):
        return self.amino_mapper.get(codon, "")


   

    def build_protein(self, phrase): #Here's the main problem
        protein = []
        i = 0
        while i < len(phrase):
            codon = phrase[i: i + 3]
            amino = self.translate_amino(codon)
            if amino:
                protein.append(amino)
            elif amino == "tag","tga","taa":
                break amino
                
            else:
                print(f"The codon {codon} is not in self.amino_mapper")
            i += 3
        return protein

但是,我遇到了一些错误。有谁知道如何解决它们。

顺便说一句,主要问题出在 def build_protein 中,它在我尝试破坏代码的情况下引发了语法错误

标签: pythondjango

解决方案


break 语句不返回任何值,您可以在跳出循环之前设置一个变量,然后检查循环中的值

def build_protein(self, phrase): #Here's the main problem
    protein = []
    i = 0
    while i < len(phrase):
        codon = phrase[i: i + 3]
        amino = self.translate_amino(codon)
        if amino:
            protein.append(amino)
        elif amino == "tag","tga","taa":
            new_amino=amino
            break
            
        else:
            print(f"The codon {codon} is not in self.amino_mapper")
        i += 3
    if new_amino:
       # do whatever
    return protein

推荐阅读