【问题标题】:Validate user's input from dictionary从字典验证用户的输入
【发布时间】:2021-10-16 08:22:16
【问题描述】:

我正在尝试验证用户输入的 2 个选项(一个是 int,一个是单词)。我尝试使用 try 和 except 值,但是它们似乎只是破坏了程序。基本上我只需要用户在轮到人类时只能输入 S、D 或 Q,而在比赛策略中只能输入 1,2 或 3。

这两种验证是

human_input_map = {
    's': 'Steal',
    'd': 'Deal',
    'q': 'Quit'
}

#Human's turn
human = input('Steal, Deal or Quit [s|d|q]?: ')              
human = human_input_map[human]
    

print('1. Always Steal')
print('2. Always Deal')
print('3. Random\n')

comp_strat = int(input('Which strategy for the computer [1,2,3]? '))
print(" ")
    
    sd = ["Steal", "Deal"]
    if comp_strat == int(1):
        comp_choice = 'Steal'
    elif comp_strat == int(2):
        comp_choice = 'Deal'
    elif comp_strat == int(3):
        comp_choice = random.choice(sd)

一如既往地感谢你的智慧!

【问题讨论】:

    标签: python validation input


    【解决方案1】:

    好吧,您可以简单地检查用户的输入是否是您预定义字典中的键!

    human_input_map = {
        's': 'Steal',
        'd': 'Deal',
        'q': 'Quit'
    }
    
    #Human's turn
    human = input('Steal, Deal or Quit [s|d|q]?: ').lower()
    if human not in human_input_map:
        # add your logic here
        print("Your input is not valid!")
    else:
       human = human_input_map[human]
    

    您也可以对其他输入使用相同的方法!

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 2017-07-22
      • 2019-10-17
      相关资源
      最近更新 更多