Python:为什么它总是说无效语法?
我编写这个程序是为了能够从用户输入中找到A/U和C/G对的数量。当我运行它时,它不断地说“无效语法”,同时以红色突出显示while循环之后的第一个“else:”。有人知道我需要改变什么来修复它吗Python:为什么它总是说无效语法?,python,Python,我编写这个程序是为了能够从用户输入中找到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
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()
您有一个
else:
未附加到任何if
、for
、while
或try
语句,这是非法的
如果您想让else
在的同时附加到,那么解决方案很简单:更改缩进以附加它:
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.")
请参阅教程中的(以及语言参考中的完整详细信息)。您的else
需要缩进到与while
相同的级别,这在本例中没有实际意义,因为循环中没有中断,或者您需要在前面的某一行添加一个,如果。我看到两件显而易见的事情:
def main():
之后的所有内容都应缩进李>
Else
的缩进级别应与while
相同。它不是孩子,而是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.")
没有任何而或其他:
下面的代码段也应该做同样的事情:
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.')
为什么它总是说无效语法?
=>通常是因为您的语法无效。在你的例子中,你的else缩进与任何if、for或while都不匹配。作为旁注,这不是一个“编码风格”的问题。编码风格是在不同的合法方式之间进行选择,以编写或布局等效的、有效的代码,而不是首先编写有效的代码。但在这种情况下,始终会调用else
块。没有意义。@OlehPrypin你的缩进很差的或者就更没有意义了。@OlehPrypin:是的,但是试图猜测OP到底想做什么是一个纸杯游戏。也许他想在第一次打印后中断
,在这种情况下,他需要添加一个中断
。或者他想跟踪是否有任何打印
s发生,如果没有,他只做其他
,在这种情况下,他滥用了其他
。或者他想要完全不同的东西。我不知道,但无论如何,他必须先编译代码,然后才能决定下一步该怎么做。@Hyperboreus:我不认为OlehPrypin是这里的OP。除了他的首字母是“OP”以外:)对不起你们两个。由于OP的循环没有退出条件,并且初始条件中的变量从未改变,我猜while
s应该是if
s。但这只是咨询我的水晶球。