所以我对Python(和这个网站)非常陌生,我正在尝试为我的合作伙伴创建一个抽认卡循环来帮助她学习,我已经生成了一个没有任何实际术语和定义的测试版本(目前)但是当我尝试使用 elif or else 在 Python IDLE 3.11 中创建循环,它只是声明“无效语法”并显示 elif or else 并突出显示“e”,以下是供参考的测试代码:
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 = 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.')
# Choose a random entry from the glossary
random_word = random.choice(list(glossary.keys()))
# Print the random entry to the screen
print("flashcard:")
print(random_word)
# Wait for the user to press Enter
input("Press Enter to reveal the definition...")
#Print the definition of the entry
print(glossary[random_word])`
在尝试创建循环之前我已经测试了所有内容,并且一切正常,有人可以帮忙吗?
谢谢!
我尝试更改 elif 和 else 但没有这样的运气,我不知道这种情况有任何其他替代方案。
这是一个缩进问题。您正在使用 Python 进行编码,而不是某种对空格不敏感的语言。您的 elif 和 else 语句需要与它们关联的 if 语句保持一致。
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
else:
print('You need to enter either q or s.')