每次运行此代码时都会出现语法错误。我不明白为什么我的脚本中的其他地方,我使用相同的结构,它工作正常。
我首先得到elif region == 2:line的语法错误。然后,我得到一堆缩进错误。我一直玩弄缩进没有用。希望有人能发现问题。
提前致谢。
def main():
back2main = "y"
while back2main == "y":
print("Main Menu");print("1.)Highest Rainfall in one Day");print("2.)Wettest Location in Ireland");print("3.)Average Monthly Raindays");print("4.)[Construct Unique Query]");print("5.)Exit")
choice = input("Please select one of options 1:5 above:")
if choice == 1:
print("1.)Cork");print("2.)Belfast");print("3.)Dublin");print("4.)Galway");print("5.)Limerick")
region = input("Please enter a city from the numbered list above:")
if region == 1:
corkRain = open("CorkRainfall.txt","r")
highestRain = 0.0
for line in corkRain:
data = line.split(" ")
if float(data[3]) > highestRain:
highestRain = float(data[3])
print("Highest rainfall in a single day for Cork: " + str(highestRain) + " mm")
corkRain.close()
back2main = raw_input("Return to Main Menu? (y/n):")
elif region == 2:
belfastRain = open("BelfastRainfall.txt","r")
highestRain = 0.0
for line in belfastRain:
data = line.split(" ")
if float(data[3]) > highestRain:
highestRain = float(data[3])
print("Highest rainfall in a single day in Belfast: ") + str(highestRain)
答案 0 :(得分:2)
elif
块必须与其上方的if
块垂直位于同一位置。这意味着elif
下的所有代码(包括elif
)都应该向左移动一个标签。
答案 1 :(得分:2)
你的问题在这里:
print("Highest rainfall in a single day for Cork: " + str(highestRain) + " mm")
corkRain.close()
back2main = raw_input("Return to Main Menu? (y/n):")
如果你希望它们位于第一个if下,那么这些行应该是一个缩进的级别。
执行被解释为超出之前的范围,下一个是"如果"而不是" elif"或者如果你想要属于上一个,如果它应该是一个缩进权。
答案 2 :(得分:2)
我建议尝试这个:
def main():
back2main = "y"
while back2main == "y":
print("Main Menu\n1.)Highest Rainfall in one Day\n2.)Wettest Location in Ireland\n3.)Average Monthly Raindays\n4.)[Construct Unique Query]\n5.)Exit")
choice = input("Please select one of options 1:5 above:")
if choice == 1:
print("1.)Cork\n2.)Belfast\n3.)Dublin\n4.)Galway\n5.)Limerick")
region = input("Please enter a city from the numbered list above:")
if region == 1:
corkRain = open("CorkRainfall.txt","r")
highestRain = 0.0
for line in corkRain:
data = line.split(" ")
if float(data[3]) > highestRain:
highestRain = float(data[3])
elif region == 2:
belfastRain = open("BelfastRainfall.txt","r")
highestRain = 0.0
for line in belfastRain:
data = line.split(" ")
if float(data[3]) > highestRain:
highestRain = float(data[3])
print("Highest rainfall in a single day for Cork: " + str(highestRain) + " mm")
corkRain.close()
back2main = raw_input("Return to Main Menu? (y/n):")
print("Highest rainfall in a single day in Belfast: ") + str(highestRain)
您可以使用新的换行符(\ n)替换多个print语句,并且需要缩进第一行下面的所有代码。此外,由于线条,elif正在破碎:
print("highest rainfall...
corkRain.close()
back 2main = ...