【问题标题】:Prompting for input until 2 blank lines are given提示输入直到给出 2 个空行
【发布时间】:2016-12-07 20:07:33
【问题描述】:

我需要提示用户输入,直到连续给出 2 个空行,请注意,为清楚起见,输入读取中可能有空行,我需要两个空行背靠背在它中断之前.

到目前为止,我想出了这个:

def gather_intel():
    done = False
    while done is False:
        data = raw_input("Copy and paste the work log: ")
        if data is None:
            done = True

一旦给出一个空行,这将如何结束,我还尝试向其中添加另一个 while 循环:

def gather_intel():
    done = False
    while done is False:
        data = raw_input("Copy and paste the work log: ")
        while data != "" + "\n" + "":
            data = raw_input("Copy and paste the work log: ")
            if data == "" + "\n" + "":
                done = True

然而,这是一个无限循环,永远不会结束。如何提示用户输入,直到有两个空行连续输入?

【问题讨论】:

    标签: python python-2.7 input


    【解决方案1】:
    number_of_empty_responses = 0
    while True:
        data = raw_input("Copy and paste the work log: ")
        if data == "":
            number_of_empty_responses += 1
            if number_of_empty_responses == 2:
                break
        else:
            number_of_empty_responses = 0
            pass # Received data, perform work.
    

    【讨论】:

    • 连续2个空行,抱歉没有指定
    • 如用户在两个连续提示下按“Enter”键?
    • 是的,先生,就是这样
    • 如果为了清楚起见,读取的数据中有空行,上面的代码将在恰好给出两个空行时中断..
    • 那么你需要在你的问题中澄清,因为它对于你到底想要达到的目标是模棱两可的。
    【解决方案2】:

    为了未来的我或其他人。 input 直到 2 个连续的换行符:

    def handy_input(prompt='> '):
        'An `input` with 2 newline characters ending.'
    
        all_input_strings = ''
    
        # prompt the user for input
        given_input = input(prompt)
        all_input_strings += given_input
        # and handle the two newline ending                                                                                                           
        while given_input:
            # if previous input is not empty prompt again
            given_input = input('')
            all_input_strings += '\n' + given_input
    
        return all_input_strings
    

    问题的答案用 2 个空行:

    def empty_lines_input(prompt='> ', n_lines=2):
        'An `input` with `n_lines` empty line ending.'
    
        all_input_strings = ''
    
        # prompt the user for input
        given_input = input(prompt)
        all_input_strings += given_input
        # and handle the two newline ending                                                                                                           
        while n_lines>0:
            # if previous input is not empty prompt again
            given_input = input('')
            all_input_strings += '\n' + given_input
            # check if it was an empty line
            if not given_input:
                n_lines -= 1
            else:
                n_lines = 2
    
        return all_input_strings
    

    【讨论】:

      猜你喜欢
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多