【问题标题】:Continues variable not triggering while loop连续变量不触发while循环
【发布时间】:2020-04-26 05:15:34
【问题描述】:

抱歉,如果这是重新发布。我正在尝试使用 continue 变量和 if/else 语句编写一个 while 循环。我的问题是我的continue 变量被忽略了,到目前为止我找不到问题。到目前为止,我已将 while continues == 'y' 条件移到 else 块中,现在我对为什么忽略此 var 感到有些困惑。

代码:

def add_to_existing_file(data):
# data[0]-api response
# data[1]-city
# infile-file object returned from openFile()
# file_name- file name string. check filetype & report version.

continues = 'y' # set up continue variable
while continues == 'y':
    file_name = input("Enter File Path to file to be appended: ") # get file from user
    if file_name is False:
        print("Now Creating Excel File..") # create condition for no user response.
        return # if empty response exit function
    else:
        infile = appends.openFile(file_name)  # open file to work with. Returns file object.
        added_data = appends.journal_report_1_to_df(infile, file_name, data[0], data[1]) # append selected file to existing df
    continues = input("Do you want to append another file? Y or N").lower() # check if new file
    return added_data # return new df w/appended data

【问题讨论】:

    标签: python-3.x while-loop


    【解决方案1】:

    问题发生在最后一行。您将在第一次迭代结束时返回,该迭代退出循环。这可以通过将返回移动到外部范围来解决。

    def add_to_existing_file(data):
        # data[0]-api response
        # data[1]-city
        # infile-file object returned from openFile()
        # file_name- file name string. check filetype & report version.
    
        continues = 'y' # set up continue variable
        while continues == 'y':
            file_name = input("Enter File Path to file to be appended: ") # get file from user
            if file_name is False:
                print("Now Creating Excel File..") # create condition for no user response.
                return # if empty response exit function
            else:
                infile = appends.openFile(file_name)  # open file to work with. Returns file object.
                added_data = appends.journal_report_1_to_df(infile, file_name, data[0], data[1]) # append selected file to existing df
            continues = input("Do you want to append another file? Y or N").lower() # check if new file
    
        return added_data # return new df w/appended data
    

    【讨论】:

      【解决方案2】:

      如果您让第二个返回行(返回 added_data # return new df w/appended data)与您的 while 行具有相同的缩进,它应该可以工作。作为 continue 循环的基本大纲:

      def function
         continues = 'y'
         while
            if :
            elif :
            else :
            print
            continue ?
         return
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-11
        • 1970-01-01
        • 2022-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-24
        相关资源
        最近更新 更多