【问题标题】:Stop program from outputting rest of code when invalid number is entered输入无效数字时停止程序输出其余代码
【发布时间】:2019-10-07 03:35:44
【问题描述】:

我想做一个一次只输出一个问题的代码。

我有一个交互式代码,允许某人输入某个范围内的某些数字,即; “0-3”。

但是,大约有 5 个问题会提示用户输入数字。

因此,如果有人输入 Q1:“4”,输出仍将显示以下问题。但是,如果发生这种情况,我希望它显示“无效号码!再试一次”。

是否有特定的代码可以阻止这种情况发生?

到目前为止:

if inp == 0:

    out = "Beginner"

elif inp == 1:

    out = "Intermediate"

elif inp == 2:

    out = "Advanced"

else:

    f=1

    if f > 3:

        print('Invalid input!')

        return

(其余代码在需要时使用 return)

【问题讨论】:

    标签: python input output


    【解决方案1】:

    那么您应该使用while 循环并在用户未选择有效输入时继续显示问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多