“如果选择......”继续下一个“如果选择......”

时间:2013-11-18 11:57:13

标签: python

您好我是python的新手,我的代码段有问题。在一个“if”语句之后,当我不想要它时,我的代码会进入下一个“if”语句。我已经尝试过elif,但它提出了无效的语法。

 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.

“纤维,一种无法消化的营养素”。我希望它回到选择菜单。我该怎么办?

2 个答案:

答案 0 :(得分:3)

将第二个if更改为elif,并将其下方的所有内容移至与print相同的缩进级别:

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')

仔细阅读the following article - 它解释了Python中的缩进是如何工作的。

答案 1 :(得分:0)

就是这样,

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)