【问题标题】:Breaking a forloop打破 for 循环
【发布时间】:2021-03-11 20:30:18
【问题描述】:

我目前正在开发我的第一个网站。一种 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 中,它在我尝试破坏代码的情况下引发了语法错误

【问题讨论】:

  • 你能解释一下你为什么用 HTML 和 CSS 标记这个吗?它们看起来根本不相关,除非我遗漏了什么
  • 什么错误?你能把它们也贴出来吗?
  • 你认为amino == "tag","tga","taa" 是什么意思?
  • 在尝试这样的项目之前,您确实应该确保您的基础更加扎实。你会先跑,然后才能走路。
  • 停止循环包含在任何有关循环的教程中。 Stack Overflow 并不打算取代现有的教程和文档。请提供预期的MRE。显示中间结果与预期结果的偏差。我们应该能够将您的代码块粘贴到文件中,运行它并重现您的问题。这也让我们可以在您的上下文中测试任何建议。发布 170 行代码是多余的;要求我们教你一个基本的语言功能是题外话。

标签: python django


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    if amino:
        protein.append(amino)
    elif amino == "tag","tga","taa":
    

    If/else 语句从上到下执行,在您的情况下,elif 永远不会被执行,因为即使amino == 'tag' if 语句被执行。 break amino 也不是一个有效的语法,你应该这样写 elif:

    elif amino in ("tag","tga","taa"):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多