In MatLab, unless I add ; at the end of the line, I can just run and see what this code is doing. For example if I code
x=0
for i=1:1:3
x=x+1
end
then I will see that
x=0
x=1
x=2
x=3
appearing in the window.
That way, I can see the process of my code, and so I can easily fix the error when there is.
How can I do the same thing in Python?
I know I can just add print to make it happen like
for i in list
print('i is:', i)
i=i+1
But this makes the whole code too messy. Is there a MatLab-like way to do this?
解决方案
I am not familiar with matlab, but from what you are explaining, you seem to be wanting to trace your code to see where errors come up? You can do this through pdbtrace.
Let me know if this is what you are looking for.
Here is a quick how-to on how to use pdbtrace using your code sample:
import pdb
l = [1, 2, 3, 4]
pdb.set_trace()
for i in l:
print('i is:', i)
i = i+1
So, when you run this, you will then have the ability to control the flow of the app. You hit 'n' for the next step in your code, and you can see what it is doing.
I strongly suggest reading this, as it is an excellent tutorial:
Furthermore, what I actually recommend even more, is using an IDE that has a fully functional debugger. I am partial to PyCharm, which you can download for free here: https://www.jetbrains.com/pycharm/download/