Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialja5on
10,338 PointsCan I show the line number in Python?
For example if I do this:-
print("code")
print("code")
print("code")
print("code")
print("code")
print("code")
print("code")
print("code")
etc
Can I also get the line that each print is used on to show in the running of the program?
This might seem a strange request, but is it doable ??
Thanks Guys
3 Answers
Steven Parker
231,261 PointsThere's a module called "inspect" that has methods for getting that kind of information:
from inspect import currentframe, getframeinfo
f = currentframe()
print(getframeinfo(f).lineno, "code")
print(getframeinfo(f).lineno, "code")
# ...etc.
ja5on
10,338 PointsWould it be possible to enclose an code block/several lines of code with just one print(getframeinfo(f).lineno, "code") ? I feel i've wrote that wrong - but if you get what i'm trying to say
Steven Parker
231,261 PointsSure, but it would only print the line number of the print
statement itself.
Or did you want to just number output lines? You could do that with a loop and a counter without inspect
.
ja5on
10,338 Pointsahh why I didn't think of a loop! of course thanks
ja5on
10,338 Pointsja5on
10,338 PointsI'm using Visual studio and the terminal doesn't supply line numbers from code that's run.
However thanks that's very interesting.