【问题标题】:How can I input a value as a string and then input a int value without having two input boxes?如何在没有两个输入框的情况下输入一个值作为字符串,然后输入一个 int 值?
【发布时间】:2015-12-04 05:12:56
【问题描述】:

我正在编写代码,用户必须猜测一个数字并输入它,并且他们可以在其中键入“退出”、“退出”或“退出”,然后它会结束程序。

我有一个 while 循环,一旦达到六次尝试的限制,程序就会结束,并且在其中有 input() 可以猜出数字。我知道在将 input() 转换为整数之前,我需要测试字符串“quit”、“QUIT”或“Quit”,但如果没有 input(),我不知道该怎么做检查字符串和检查整数。

有什么建议吗?

【问题讨论】:

  • 你能发布你的代码吗?
  • 到目前为止你能发布你的代码吗?
  • 我能弄明白。感谢大家的帮助。

标签: python string input while-loop int


【解决方案1】:

无论您输入什么都是字符串,因此在尝试从中创建 int 对象之前,只需将其与 QUIT 进行比较是没有害处的。

tries = 0
while tries < 6:

    value = raw_input("Enter a number, or 'quit' to quit: ")  # input() in Python 3.x
    if value.upper() == 'QUIT':
        sys.exit()

    try:
        value = int(value)
    except ValueError:
        continue  # Return to the top of the loop for another value

    # Process the input integer...

【讨论】:

    【解决方案2】:

    由于您在输入后将其转换为 int,因此我假设您使用的是 Python 3。

    在主循环中尝试以下操作:

    a = input()
    if(a.isdigit()):
        n = int(a)
        #main code here
    else:
        #check for "quit" here as shown below
        if(a.upper == 'QUIT'):  #a.upper() will convert the string into capital letters
            #You need to break from the main loop
            break
    

    如果您使用的是 Python 2.7 或更低版本,那么将上述示例代码中的 input() 替换为 raw_input() 即可解决您的问题。

    raw_input() 接受任何类型的输入,从而解决您的问题。

    【讨论】:

      【解决方案3】:

      也许你正在寻找这样的东西(python 2.6/7):-

      lucky_number = 5
      tries = 6
      while tries:
        inp = raw_input("User input: ")
        if inp.isdigit() and int(inp) == lucky_number:
          return True
        elif inp.lower() == 'quit':
          break
        tries -= 1
      return False  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-16
        • 2017-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多