-3

我编写这个程序是为了能够从用户输入中找到 A/U 和 C/G 对的数量。当我运行它时,它一直说“无效的语法”,同时以红色突出显示 while 循环之后的第一个“else:”。有谁知道我需要改变什么来修复它?

def main():

    first = input("Please enter the RNA sequence for which you wish to find the number of pairs. \nFirst line:")
    second = input("Second String:")

    a1base = first.count('A')
    u1base = first.count('U')
    c1base = first.count('C')
    g1base = first.count('G')
    a2base = second.count('A')
    u2base = second.count('U')
    c2base = second.count('C')
    g2base = second.count('G')

    while (a1base >= 1) and (u1base >= 1) or (a2base >= 1) and (u2base >= 1):
        abases = (a1base+ a2base)
        ubases = (u1base + u2base)
        firstset = min(abases, ubases)
        print("You have", firstset,"A/U bases.")
        else:
            print("You have zero A/U bases.")

    while (c1base >= 1) and (g1base >= 1) or (c2base >= 1) and (g2base >= 1):
        cbases = (c1base + c2base)
        gbases = (g1base + g2base)
        secondset = min(cbases, gbases)
        print("You have", secondset,"C/G bases.")
        else:
            print("You have zero C/G bases.")



main()
4

4 回答 4

3

你有一个else:不附加到任何if, for, while, ortry语句的,这是非法的。

如果您打算else将 附加到while,则解决方案很简单:更改缩进以附加它:

while (a1base >= 1) and (u1base >= 1) or (a2base >= 1) and (u2base >= 1):
    abases = (a1base+ a2base)
    ubases = (u1base + u2base)
    firstset = min(abases, ubases)
    print("You have", firstset,"A/U bases.")
else:
    print("You have zero A/U bases.")

请参阅教程中的语句和循环子句(以及break语言continue参考else复合语句以获取完整详细信息)。

于 2013-11-06T22:54:34.343 回答
1

else需要缩进与您相同的级别while,在这种情况下这实际上没有意义,因为break您的循环中没有,或者您需要if在它之前的某行上添加一个。

于 2013-11-06T22:54:56.797 回答
0

我看到两件明显的事情:

  1. 后面的所有内容都def main():应该缩进;
  2. Else应该与 . 的缩进级别相同while。它不是孩子,而是 的兄弟姐妹while
于 2013-11-06T22:56:54.730 回答
0

其他人已经解释了这个错误。

尝试将while循环更改为:

abases = (a1base+ a2base)
ubases = (u1base + u2base)
firstset = min(abases, ubases)
print("You have", firstset if firstset else 'zero',"A/U bases.")

cbases = (c1base + c2base)
gbases = (g1base + g2base)
secondset = min(cbases, gbases)
print("You have", secondset if secondset else 'zero',"C/G bases.")

没有任何whileelse:

以下代码段也应该做同样的事情:

first = input("Please enter the RNA sequence for which you wish to find the number of pairs. \nFirst line:")
second = input("Second String:")
bases = {k: (first + second).count(k) for k in 'AUCG'}
print('You have', min(bases['A'], bases['U']), 'A/U bases.')
print('You have', min(bases['C'], bases['G']), 'C/G bases.')
于 2013-11-06T23:13:35.340 回答