我编写了这个程序,以便能够从用户输入中找到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()
答案 0 :(得分:3)
您有else:
未附加到任何if
,for
,while
或try
声明,这是非法的。
如果你想将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
and continue
Statements, and else
Clauses on Loops(以及语言参考中的Compound statements以获取完整详情。)
答案 1 :(得分:1)
您的else
需要缩进到与while
相同的级别,在这种情况下这是没有意义的,因为您的循环中没有break
,或者您需要在它之前的某一行添加if
。
答案 2 :(得分:0)
我看到两件显而易见的事情:
def main():
之后的所有内容都应缩进; Else
应与while
处于同一级别的缩进。它不是孩子,而是while
的兄弟姐妹。答案 3 :(得分: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.")
没有任何while
或else:
。
以下代码段也应该做同样的事情:
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.')