Python &引用;如果选择……”;“继续下一步”;如果选择……”;
您好,我是python的新手,我的一段代码有问题。在一个“if”语句之后,我的代码在我不希望的情况下继续执行下一个“if”语句。我尝试过elif,但它产生了无效的语法Python &引用;如果选择……”;“继续下一步”;如果选择……”;,python,Python,您好,我是python的新手,我的一段代码有问题。在一个“if”语句之后,我的代码在我不希望的情况下继续执行下一个“if”语句。我尝试过elif,但它产生了无效的语法 print( """ Flash Card Quiz 0 - Show Keywords 1 - Take the Test 2 - Exit """ ) choice = input("Choice: ") print() #ShowKeyword
print(
"""
Flash Card Quiz
0 - Show Keywords
1 - Take the Test
2 - Exit
"""
)
choice = input("Choice: ")
print()
#ShowKeywords
if choice == "0":
fp = open('keywords.txt')
while 1:
line = fp.readline()
if not line:
break
print (line)
# TaketheTest
if choice == "1":
print("Here is your Keyword")
import random
with open('keywords_1.txt') as f:
a = random.choice(list(f)).strip()
print (" ")
print ("------", a)
这就是我们正在展示的
fibre,A nutrient that cannot be digested.
------ photosynthesis
Here are your options, select A, B or C, whichever is correct.
Press the enter key to continue.
在“纤维,一种不能被消化的营养素”之后,我想让它回到选择菜单。我该怎么做呢?将第二个
if
更改为elif
,并将其下方的所有内容移动到与打印
相同的缩进级别:
elif choice == "1":
print("Here is your Keyword")
import random
with open('keywords_1.txt') as f:
a = random.choice(list(f)).strip()
print (" ")
print ("------", a)
编辑:如果您希望在用户做出第一个选择后让他(她)做出另一个选择,则将您提供的所有代码包装到while True:
循环中,并添加两个新选项:
elif choice == "2":
break
else:
print('Incorrect option')
仔细阅读-它解释了Python中缩进的工作原理。它是这样的
print(
"""
Flash Card Quiz
0 - Show Keywords
1 - Take the Test
2 - Exit
"""
)
while True:
choice = input("Choice: ")
print()
#ShowKeywords
if choice == "0":
fp = open('keywords.txt')
while True:
line = fp.readline()
if not line:
break
print (line)
# TaketheTest
elif choice == "1":
print("Here is your Keyword")
import random
with open('keywords_1.txt') as f:
a = random.choice(list(f)).strip()
print (" ")
print ("------", a)
您可以使用while循环继续上面的操作。我以前没有使用过,请您展开一下好吗?它的输出完全相同。您是否缩进了下面的行?Python使用空格来管理作用域,因此如果缩进错误,那么代码就是错误的。它不再打印下一个if语句,但不会返回菜单。现在如何使用选项==2关闭程序?在
import random
之前,只需添加以下内容elif choice='2':sys.exit(0)