Python 输入无效数字时,停止程序输出剩余代码
我想做一个每次只输出一个问题的代码 我有一个交互式代码,允许某人输入某个范围内的特定数字,即;"0-3". 但是,大约有5个问题提示用户输入数字 因此,如果有人输入Q1:“4”,输出仍将显示以下问题。但是,如果发生这种情况,我希望它显示“无效号码!重试” 是否有特定的代码阻止这种情况发生 迄今为止,我已:Python 输入无效数字时,停止程序输出剩余代码,python,input,output,Python,Input,Output,我想做一个每次只输出一个问题的代码 我有一个交互式代码,允许某人输入某个范围内的特定数字,即;"0-3". 但是,大约有5个问题提示用户输入数字 因此,如果有人输入Q1:“4”,输出仍将显示以下问题。但是,如果发生这种情况,我希望它显示“无效号码!重试” 是否有特定的代码阻止这种情况发生 迄今为止,我已: 如果inp==0: out=“初学者” elif inp==1: out=“中级” elif inp==2: out=“高级” 其他: f=1 如果f>3: 打印('无效输入!') 返回
如果inp==0:
out=“初学者”
elif inp==1:
out=“中级”
elif inp==2:
out=“高级”
其他:
f=1
如果f>3:
打印('无效输入!')
返回
(其余代码在需要时使用return)如果用户没有选择有效的输入,则应在循环时使用
,并继续显示问题:
def display_question(sentence,
choices=['Beginner', 'Intermediate', 'Advanced']):
again = True
while again:
inp = input(sentence).strip()
# Check if the user entered a digit
if inp.isdigit():
user_number = int(inp)
if user_number >= 0 and user_number < len(choices):
print("Your choice is {}".format(choices[user_number]))
return choices[user_number]
# If the input is not valid, display error message and retry
print('Invalid input! Try again')
display_question('Make your choice (0: Beginner, 1: Intermediate, 2: Advanced): ')