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 trial

Python

Can 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
Steven Parker
231,007 Points

There'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.

I'm using Visual studio and the terminal doesn't supply line numbers from code that's run.

However thanks that's very interesting.

Would 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
Steven Parker
231,007 Points

Sure, 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.

ahh why I didn't think of a loop! of course thanks