[Python] Why does this loop execute 4 times?

  • Context: Python 
  • Thread starter Thread starter Hercuflea
  • Start date Start date
  • Tags Tags
    Loop Python
Click For Summary

Discussion Overview

The discussion revolves around a Python code snippet that reads an input file to extract grid size information. Participants are exploring why a loop within the function executes four times, despite the expectation that it should only run once for each relevant line in the file. The scope includes technical explanation and debugging of the code.

Discussion Character

  • Technical explanation, Debugging

Main Points Raised

  • One participant questions the number of lines in the input file, suggesting that the loop executes for each line, which could explain the multiple executions.
  • Another participant notes the presence of continue statements in the if clauses, questioning their necessity.
  • A participant mentions that the function might be called multiple times elsewhere in the code, which could lead to the observed behavior.
  • One participant confirms that they were indeed calling the function four times from another part of their code, leading to the confusion.
  • A suggestion is made to use a standard library component for reading files in a specific format, which could improve efficiency and robustness.

Areas of Agreement / Disagreement

Participants generally agree that the function's multiple executions are likely due to it being called multiple times, but there is no consensus on the necessity of the continue statements or the best approach for reading the input file.

Contextual Notes

The discussion does not resolve the necessity of the continue statements or the implications of using a standard library component, as these remain open for further exploration.

Hercuflea
Messages
593
Reaction score
49
I've written a code which reads in an input file and extracts a number which represents a grid size, from lines in the file which can contain arbitrary characters. The extraction of the data seems to be working, but for some reason the loop executes 4 times and then moves on to the next function in my code...Why does my loop execute 4 times? I've been stuck on this for a while now.

Python:
def BOUTinp_search():
    with open('BOUT.inp', 'r') as boutinput:
        for line in boutinput:
            if '[mesh]' in line:
                print '\nFound mesh options.'
                continue
            elif 'nx =' in line:
                xnumpts = int(filter(str.isdigit, line))
                print('Recovered number of x gr'
                'id points.')
                print 'x grid size: ', xnumpts
   
                continue
            elif 'ny =' in line:
                ynumpts = int(filter(str.isdigit, line))
                print('Recovered number of y gr'
                'id points.')
                print 'y grid size: ', ynumpts
                continue
            elif 'dx =' in line:
                dx = float(filter(str.isdigit, line))
                print 'Recovered x spacing.'
                print 'x grid spacing: ', dx
                continue

            elif 'dy =' in line:
                dy = float(filter(str.isdigit, line))
                print 'Recovered y spacing.'
                print 'y grid spacing: ', dy
                continue

    return [xnumpts, ynumpts, dx, dy]

Output:

Code:
[me@dir]$ python file.py

Found mesh options.
Recovered number of x grid points.
x grid size:  260
Recovered number of y grid points.
y grid size:  1
Recovered x spacing.
x grid spacing:  2.0
Recovered y spacing.
y grid spacing:  1.0

Found mesh options.
Recovered number of x grid points.
x grid size:  260
Recovered number of y grid points.
y grid size:  1
Recovered x spacing.
x grid spacing:  2.0
Recovered y spacing.
y grid spacing:  1.0

Found mesh options.
Recovered number of x grid points.
x grid size:  260
Recovered number of y grid points.
y grid size:  1
Recovered x spacing.
x grid spacing:  2.0
Recovered y spacing.
y grid spacing:  1.0

Found mesh options.
Recovered number of x grid points.
x grid size:  260
Recovered number of y grid points.
y grid size:  1
Recovered x spacing.
x grid spacing:  2.0
Recovered y spacing.
y grid spacing:  1.0
 
Last edited by a moderator:
Technology news on Phys.org
Hercuflea said:
I've written a code which reads in an input file and extracts a number which represents a grid size, from lines in the file which can contain arbitrary characters. The extraction of the data seems to be working, but for some reason the loop executes 4 times and then moves on to the next function in my code...Why does my loop execute 4 times? I've been stuck on this for a while now.

Python:
def BOUTinp_search():
    with open('BOUT.inp', 'r') as boutinput:
        for line in boutinput:
            if '[mesh]' in line:
                print '\nFound mesh options.'
                continue
            elif 'nx =' in line:
                xnumpts = int(filter(str.isdigit, line))
                print('Recovered number of x gr'
                'id points.')
                print 'x grid size: ', xnumpts
  
                continue
            elif 'ny =' in line:
                ynumpts = int(filter(str.isdigit, line))
                print('Recovered number of y gr'
                'id points.')
                print 'y grid size: ', ynumpts
                continue
            elif 'dx =' in line:
                dx = float(filter(str.isdigit, line))
                print 'Recovered x spacing.'
                print 'x grid spacing: ', dx
                continue

            elif 'dy =' in line:
                dy = float(filter(str.isdigit, line))
                print 'Recovered y spacing.'
                print 'y grid spacing: ', dy
                continue

    return [xnumpts, ynumpts, dx, dy]

Output:

Code:
[me@dir]$ python file.py

Found mesh options.
Recovered number of x grid points.
x grid size:  260
Recovered number of y grid points.
y grid size:  1
Recovered x spacing.
x grid spacing:  2.0
Recovered y spacing.
y grid spacing:  1.0

Found mesh options.
Recovered number of x grid points.
x grid size:  260
Recovered number of y grid points.
y grid size:  1
Recovered x spacing.
x grid spacing:  2.0
Recovered y spacing.
y grid spacing:  1.0

Found mesh options.
Recovered number of x grid points.
x grid size:  260
Recovered number of y grid points.
y grid size:  1
Recovered x spacing.
x grid spacing:  2.0
Recovered y spacing.
y grid spacing:  1.0

Found mesh options.
Recovered number of x grid points.
x grid size:  260
Recovered number of y grid points.
y grid size:  1
Recovered x spacing.
x grid spacing:  2.0
Recovered y spacing.
y grid spacing:  1.0
How many lines are there in your input file? You have a loop that executes for each line in this file. Also, I don't see the reason for having continue statements in each of your if clauses.

BTW, I removed your "spoiler" tags. Since you're asking a question about code, having your code and output hidden by spoiler tags didn't seem very useful.
 
Mark44 said:
How many lines are there in your input file? You have a loop that executes for each line in this file. Also, I don't see the reason for having continue statements in each of your if clauses.

BTW, I removed your "spoiler" tags. Since you're asking a question about code, having your code and output hidden by spoiler tags didn't seem very useful.
Hi Mark, thanks for the input.

There are currently 48 lines in the input file, but there could be more or less based on what the user's preferences are. At the moment I'm only interested in making a Cartesian grid using one of the options called "mesh" in the input file, but I'm trying to keep it as forward-compatible as possible.
I.e. I want to loop through the entire file in case I decide to read in options from some of the other sections later.

The continue statements were basically a safeguard to make sure it only executes one and only one of the if statements at each line of the file, but I suppose they aren't necessary.
 
Well, maybe the contents of BOUTinp_search() is being executed only once; but, could it be that you are calling BOUTinp_search() four times in the first place? Can't tell, you don't show your entire code.
 
gsal said:
Well, maybe the contents of BOUTinp_search() is being executed only once; but, could it be that you are calling BOUTinp_search() four times in the first place? Can't tell, you don't show your entire code.

You were right...I was actually calling the function four times in a silly way in another function. Thanks for that.
 
Assuming your section names (like `[mesh]`) are unique, there is a component in the standard library to read files in this format. It's quicker and more robust to use it, if your file structure allows it.

https://docs.python.org/3/library/configparser.html
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
Replies
3
Views
4K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K