【问题标题】:How to let the user input as many lines of input as they want until they input the "stop" word in Python?如何让用户输入任意多行的输入,直到他们在 Python 中输入“停止”字?
【发布时间】:2013-09-18 00:45:54
【问题描述】:

假设我要求用户输入书籍或其他内容中的行。我不知道他们会决定输入多少行。您如何让他们输入任意数量的行,直到他们输入一个秘密单词,例如“blueblue”。这就是我目前得到的代码。

while (blueblue == false):
line1 = input()

我们将不胜感激。

嘿,使用 Owen 的代码后,我在读取和输出一些信息时遇到了问题。我想在这里问它而不是打开另一个问题。这是我的代码:

lines = []
current_line = input()
while current_line != "blueblue":
    lines.append(current_line)
    current_line = input()
print (lines)
ints_list = []
for line_ in lines:
    for letter in line:
        if (letter == "0","1","2","3","4","5","6","7","8","9"):
             print ("hueheuheuehheuue")

现在假设用户输入是:

1 hello my name
is cmput 3.4

它只会打印“huehueheuheu”输入时的字符数。 我试过不带括号的数字,但还是不行,我什至试过“或”。 请帮忙。

【问题讨论】:

  • 您只想打印数字?我不正确理解更新的新问题。请同时指定预期输出。

标签: python input line


【解决方案1】:

有一种简单而简洁的方法可以做到这一点。

Python 3

for inputString in iter(input, "blueblue"):
    print (inputString)

Python 2

for inputString in iter(raw_input, "blueblue"):
    print (inputString)

编辑:看起来您想为遇到的每个号码打印hueheuheuehheuue。可以这样做。

for inputString in iter(raw_input, "blueblue"):
    for inputChar in inputString:
        if inputChar.isdigit():
            print ("hueheuheuehheuue")

【讨论】:

    【解决方案2】:
    lines = []
    current_line = input()
    while current_line != "blueblue":
        lines.append(current_line)
        current_line = input()
    
    # Process lines
    

    【讨论】:

      【解决方案3】:

      这几乎就是你告诉它要做的事情。

      您当前循环遍历每个字母 - 如果是数字,则打印“huehue”,如果不是,则不执行任何操作。

      因此,如果您的输入是 > in 3 或 4

      你的程序认为

      i > do nothing
      n > do nothing
      3 > huehue
      o > do nothing
      r > do nothing
      4 > huehue
      

      既然你没有说你要尝试做什么,那就是我能做到的!

      编辑 - 那是想要的输出吗? 除了您的拼写错误外,我本来希望它可以工作,但是当我加载它时,我得到了与您相同的结果。我按照我通常做的方式做了它并且它确实有效,但我不能告诉你为什么你的没有。 在这种情况下,试试这个...

      lines = []
      current_line = str(raw_input(">"))
      while current_line != "blueblue":
          lines.append(current_line)
          current_line = str(raw_input(">"))
      print (lines)
      numbers = ["0","1","2","3","4","5","6","7","8","9"]
      for line in lines:
          for letter in line:
              if letter in numbers:
                  print ("hueheuheuehheuue")
      

      输入之后,我立即意识到了问题。

      如果 (字母 == "0, "1" ... 正在检查 letter = 1,然后检查“1”,这将始终为真。像这样移动括号

      如果字母 == ("0", "1", ...

      也解决了问题。

      【讨论】:

      • 这正是我想要做的,但它写“hueheuehuehue”的次数太多了。它可以写任何东西,而不仅仅是数字......
      • @dkentre 你到底想做什么?
      • 对于输入中的每个数字我想输出一次huehueheue。
      • @dkentre 请立即查看我的答案。
      猜你喜欢
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2022-01-24
      • 2020-01-30
      • 1970-01-01
      • 2020-05-26
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多