You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python闪卡循环语法错误求助:elif/else报Invalid syntax

问题解决:Python循环中elif/else语法错误及其他代码问题

核心错误:缩进问题

你遇到的Invalid syntax是因为elif和else的缩进不正确。Python通过缩进划分代码块,elif和else必须与对应的if保持同一缩进层级,不能嵌套在if的代码块内。

你的循环代码里,elif和else缩进在了if user_input == 'q'的代码块里,导致语法错误。修正后的循环部分代码如下:

# Interactive loop
exit = False
while not exit:
    user_input = input('Enter s to show a flashcard and q to quit: ')
    if user_input == 'q':
        exit = True
    elif user_input == 's':
        show_flashcard()
    else:
        print('You need to enter either q or s.')

其他需要修正的代码问题

除了缩进,你的show_flashcard函数还有两处错误:

  1. 调用choice时未指定random模块,应该用random.choice;
  2. glossary()是错误写法,glossary是字典变量,不是函数,不需要加括号。

修正后的函数代码:

def show_flashcard():
    """Show the user a random key and ask them to define it. Show the definition when the user presses return."""
    random_key = random.choice(list(glossary))  # 直接用glossary即可获取键的列表
    print('Define: ', random_key)
    input('Press return to see the definition')
    print(glossary[random_key])

额外说明

你代码末尾的那段随机显示闪卡的代码(从random_word = random.choice(...)开始)会在循环结束后执行一次。如果这不是你想要的功能,可以删除这段代码——循环内调用show_flashcard()已经实现了闪卡交互逻辑。

完整修正后的代码:

import random

def show_flashcard():
    """Show the user a random key and ask them to define it. Show the definition when the user presses return."""
    random_key = random.choice(list(glossary))
    print('Define: ', random_key)
    input('Press return to see the definition')
    print(glossary[random_key])

# Set up glossary
glossary = {'word1':'definition1',
            'word2':'definition2',
            'word3':'definition3'}
# Interactive loop
exit = False
while not exit:
    user_input = input('Enter s to show a flashcard and q to quit: ')
    if user_input == 'q':
        exit = True
    elif user_input == 's':
        show_flashcard()
    else:
        print('You need to enter either q or s.')

内容的提问来源于stack exchange,提问作者SomethingPool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:07:18