Unreliable ending of inner loop in python - python-2.7

You know I am a long-time matlab and fortran user. Those languages use explicit end or continue statements to terminate a loop. In Python you must use indentation to identify statements that are in the loop. The example below will not run if I do not put a statement (any statement) at the first indentation level to terminate the inner loop. i.e. if you try to drop down 2 levels of indentation there is an invalid syntax error. So if you comment out the first print statement the error occurs. Is that just the way it is? Is there some kind of dummy continue or enddo statement in Python that can serve as a placeholder for this?
I get this error when using python2.7 on Linux. Note using the Spyder Python 3 environment on PC it runs fine with or without the print statement!
from numpy import *
nt=11
nres=2
t=zeros(nt)
y=zeros((nres,nt))
for it in range(nt):
if it == 0:
t[it]=0.
else:
t[it]=t[it-1]+1./(nt-1)
for ir in range(nres):
y[ir,it]=sin(pi*t[it]+ir*pi/2)
# need a statement at this level to terminate inner for loop
print('it=',it,'t=',t[it],'y(:,it)=',y[:,it])
print('end of outer loop')

Related

how to get a block of code to run only once in a loop in fortran in a case where the condition repeats

I am running a program in fortran 95. The loop contains a set of conditional actions that reverses under set limits. Please can someone advise me on how to get a block of code to run only once in a loop, such that it does repeat when the condition is met, but runs the rest of the code until the number of iterations is complete?
After reading your question several times, I think I know what you want. If you want a piece of code to always run at least once inside a do loop but possibly repeat, you can try something like this. Start with a logical variable to ensure one execution:
once = .true.
do i = 1, whatever
some code
if (once .or. (another condition)) then
once = .false.
code will always run once but possibly repeat
end if
can have more code
enddo

Debuggers not acting properly on Jupyter notebooks

I'm trying to debug some code in a Jupyter notebook. I've tried 3 4 different methods, and they all suffer from the same problem:
--Return--
None
> <ipython-input-22-04c6f5c205d1>(3)<module>()
1 import IPython.core.debugger as dbg
2 dber = dbg.Tracer()
----> 3 dber()
4 tst = huh.plot(ret_params=True)
5 type(tst)
ipdb> n
> y:\miniconda\lib\site-packages\ipython\core\interactiveshell.py(2884)run_code()
2882 finally:
2883 # Reset our crash handler in place
-> 2884 sys.excepthook = old_excepthook
2885 except SystemExit as e:
2886 if result is not None:
as you can see, the n command, which from what I understood from the pdb documentation should execute the next line (I'm assuming ipdb is just pdb adapted to work on IPython, especially since I can't find any command documentation that refers specifically to ipdb and not pdb)
s also has the same problem. This is actually what I want to do - step into the plot call (from what I understand, this is what s is supposed to do), but what I get is exactly the same as what I get from n. I also just tried r and I get the same problem.
Every example I've seen just uses Tracer()() or IPython.core.debugger.PDB().set_trace() to set a breakpoint in the line that follows the command, but both cause the same problems (and, I assume, are actually the exact same thing).
I also tried %debug (MultipleInstanceError) and %%debug (Doesn't show the code in the line being executed - just says what line, using s doesn't step into the function, just runs the line).
Edit: turns out, according to a blog post from April of this year, plain pdb should also work. It does allow me to interactively debug the notebook, but it only prints the current line being debugged (probably not a bug), and it has the same problem as IPython's set_trace() and Tracer()()
on plain IPython console, IPython's set_trace (only one I've tested) works just fine.
I encountered the same problem when debugging in Jupyter Notebook. What is working for me however, is when I call set_trace() inside a function. Why is explained here (click), though I don't really understand why others don't encounter this problem. Anyway, if you need a pragmatic solution for your problem and you want to debug a self-written function, try this:
from IPython.core.debugger import set_trace
def thisfunction(x):
set_trace() # start debugging when calling the function
x += 2
return x
thisfunction(5) # ipdb console opens and I can use 'n'
Now I can use 'n' and the debugging process runs the next line without problems. If I use the following code, however, I run into your above mentioned problem.
from IPython.core.debugger import set_trace
def thisfunction(x):
x += 2
return x
set_trace() # start debugging before calling the function.
# Calling 's' in the ipdb console to step inside "thisfunction" produces an error
thisfunction(5)
Hope this helps until somebody could solve the problem completely.

Why would a PyDev breakpoint on a return statement only work part of the time?

I have some code that calculates the price of a stock option using Monte Carlo and returns a discounted price. The final few lines of the relevant method look like this:
if(payoffType == pt.LongCall or payoffType == pt.LongPut):
discountedPrice=discountedValue
elif(payoffType == pt.ShortCall or payoffType == pt.ShortPut):
discountedPrice=(-1.0)*discountedValue
else:
raise Exception
#endif
print "dv:", discountedValue, " px:", discountedPrice
return discountedPrice
At a higher level of the program, I create four pricers, which are passed to instances of a portfolio class that calls the price() method on the pricer it has received.
When I set the breakpoint on the if statement or the print statement, the breakpoints work as expected. When I set the breakpoint on the return statement, the breakpoint is interpreted correctly on the first pass through the pricing code, but then skipped on subsequent passes.
On occasion, if I have set a breakpoint somewhere in the flow of execution between the first pass through the pricing code and the second pass, the breakpoint will be picked up.
I obviously have a workaround, but I'm curious if anyone else has observed this behavior in the PyDev debugger, and if so, does anyone know the root cause?
The issues I know of are:
If you have a StackOverflowError anywhere in the code, Python will disable the tracing that the debugger uses.
I know there are some issues with asynchronous code which could make the debugger break.
A workaround is using a programmatic breakpoint (i.e.: pydevd.settrace -- the remote debugger session: http://www.pydev.org/manual_adv_remote_debugger.html has more details on it) -- it resets the tracing even if Python broke it in a stack overflow error and will always be hit to (the issue on asynchronous code is that the debugger tries to run with untraced threads, but sometimes it's not able to restore it on some conditions when dealing with asynchronous code).

Break outside a loop, return outside a function - iPython Notebook

I have an iPython notebook that has blocks of code of which I want to be able to have the opportunity to stop at points whilst it is executing.
The code downloads a query form an API and on the first return determines the maximum rows and whether it contains sampled data.
Depending if it has sampled data, and to what extent, I would like the option to stop the code prior to the while loop which will iteratively download the full dataset.
The 'break' code I have is as below:
print "Contains sampled data? " + str(metadata["containsSampledData"])
print "Break query? -> Y"
bi = raw_input()
if bi == "Y":
break
I have tried return and break, which both give errors (though they do stop the code). In addition, I have tired quit() however I am not wanting to reset the kernal and re-import modules/create variables.
Is there any way, outside of a loop and not within a function that you can stop the code, without quitting the instance?
I think you need to rethink and rewrite the logic of your program.
print "Contains sampled data? " + str(metadata["containsSampledData"])
while True:
# Check the condition with your API stuff here
# and exit or ask everytime if the condition is true as shown below
print "Break query? -> Y"
bi = raw_input()
if bi == "Y":
break
# Continue executing your code here.
The other option is to use sys.exit() as you already tried but it will exit the program.

Strange output and branch warning when compiling

I compile a fortran 77 code using gfortran and get the following error:
10 open (23,file=outfile,status='old',access='append',err=10)
1
Warning: Branch at (1) may result in an infinite loop
This happens several times.
One of the output files looks like the following:
^L6a10È <90> ) &<9b>LÓLÓLÕ<91><90> <90> <90> È <8e><9b>LÓLÓLÕ<93>2
!MERCURY ¢¤õ/!ô<8a><8a><90> ÿ<90> ÿ<90> ÿÌÖÏ©ü}M<91>
"VENUS «}>±{©±<8b><90> ÿ<90> ÿ<90> ÿʺ93¿<8d>d<91>
However, it should just look like a table of text.
Any ideas?
Your line of code
10 open (23,file=outfile,status='old',access='append',err=10)
specifies that the open statement should transfer control to itself (label 10) in case an error is encountered, so any error could trigger an infinite loop. It also suppresses the output of error messages. If you want to just check for an error status, I would suggest using the iostat and/or iomsg (Fortran 2003) arguments:
open (23, file=outfile, status='old', access='append', iostat=ios, iomsg=str)
Here ios is an integer that will be zero if no errors occur and nonzero otherwise, and str is a character variable that will record the corresponding error message.
The err= argument in your open statement specifies a statement label to branch to should the open fail for some reason. Your code specifies a branch to the line labelled 10 which happens to be the line containing the open statement. This is probably not a good idea; a better idea would be to branch to a line which deals gracefully with an error from the open statement.
The warning from gfortran is spot on.
As to the apparent garbage in your output file, without sight of the code you use to write the garbage (or what you think are pearls perhaps) it's very difficult to diagnose and fix that problem.