【问题标题】:Preventing a user from entering a string in Python 3防止用户在 Python 3 中输入字符串
【发布时间】:2020-07-11 11:03:50
【问题描述】:

我是在 Python 3 中编写的,但是如何防止用户输入字符串?

x = int(input("If you want to play with computer, click 0. If you want to play with your friend, click 1. "))

【问题讨论】:

    标签: python input whitelist blacklist


    【解决方案1】:

    使用try/except

    while True:
        user_input = input("If you want to play with computer, click 0. If you want to play with your friend, click 1. ")
        try:
            user_input = int(user_input)
            # do something
            break
        except ValueError:
            print("input a valid choice please")
    

    【讨论】:

      【解决方案2】:

      您可以在整数转换之前添加带有str 类型的isnumeric 方法的if 语句,如下所示:

      x = input('Enter a number: ')
      
      if x.isnumeric(): # Returns True if x is numeric, otherwise False.
          int(x) # Cast it and do what you want with it.
      else: # x isn't numeric
          print('You broke the rules, only numeric is accepted.')
      

      【讨论】:

        猜你喜欢
        • 2019-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多