简体   繁体   中英

How to break an infinite loop in python?

Code below is my method definition that will calculate/get the next date depends on the terms entered by the user. My problem now is that upon running it returns an infinite loop and the date did not change. This is somehow related with my previous question, but this time I put on a button.

def calculate_schedule(self, cr, uid, ids, context=None):
    schedule_obj = self.pool.get('installment.schedule')
    sequence_obj = self.pool.get('ir.sequence')
    id = []
    _logger.info("\n\t\t\t1st .. IDS %s"%(str(ids)))
    for record in self.browse(cr, uid, ids, context=context):
        itb = record.name or sequence_obj.get(cr, uid, 'installment')
        _logger.info("\n\t\t\t2nd .. ITB %s"%(str(itb)))
        old_history = schedule_obj.search(cr, uid, [('parent_id','=',record.id)],context=context)
        _logger.info("\n\t\t\t3rd .. OLD HISTORY %s"%(str(old_history)))
        if old_history:
            schedule_obj.unlink(cr, uid, old_history, context=context)
        factor = self._get_factor(cr, uid, ids, record.terms, context=context)
        i =  0
        seq = 1
        range = 24

        while seq <= 24:
            while i < factor:
               date = datetime.strptime(record.payable_start_on, '%Y-%m-%d') + relativedelta(months=+i)
               _logger.info("\n\t\t\t4th .. Date %s"%(str(date)))
               key = str(record.id)
               temp_dict = {
                         'regular_date' : date.strftime('%Y-%m-%d'),
                         'seq' : seq,
                         'parent_id' : record.id,
                         }
               _logger.info("\n\t\t\t5th .. TEMP DICT %s"%(str(temp_dict)))
               id = schedule_obj.create(cr,uid,temp_dict,context=context)
               _logger.info("\n\t\t\t6th .. CREATED SCHEDULE %s"%(str(id)))  
            i += 1
        seq += 1
        #break
        lines = [(0,0,line) for line in schedule_obj.search(cr,uid,[('id','=',id[0])])]
        _logger.info("\n\t\t\t7th .. LINES %s"%(str(lines)))
        self.write(cr,uid,[record.id],{'child_ids':lines},context=context)
    return  True

Your commenters have already hit the nail on the head.

In python, your code decides the order in which to run based on indentation, not on brackets or other formatting. Because of this, when you have seq += 1 and i += 1 with the same indentation as the while loop, you are not running them inside the while loops, you are running them outside. Thus as the while loop conditions are based on these variables, you will never exit your loops.

The solution is simply to indent these two statements to be inside the while loops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM