python question

I am learning python and see the below line of code. I would like to know what it means

print("%.*f" % (digits, pi))

Here is the full code to return the value of pi up to first 10 digits.

AnB ArwAsked:
Who is Participating?
gelonidaConnect With a Mentor Commented:
The whole example could be something like
from math import pi
num_digits = 5

print("%.*f" % (num_digits, pi))

Open in new window


num_digits = 8
a_seventh = 1.0 / 7
print("%.*f" % (num_digits, a_seventh))

Open in new window

math.pi is a floating point variable containing  pi
a_seventh is in above example a floatingpoint variable containing the result of  dividing one by seven.

"%.*f" % (digits, a_float_value)

is a formatting string asking to display a_float_value as string with num_digits digits after the decimal point.

This a printf style / (python old style) formatting very similiar to the formatting of printf in the C language.
More documentation and examples can be found at the official documentation of python

Please note that in python you have old style formatting with % , which is a little shorter and easier for people who know C's printf
Old style formatting looks like
format_string % formatarguments 

Open in new window

But you also have the new style formatting , which is more powerful, but sometimes for simple cases 'just' more characters to type.
New style formats look like

Open in new window

If you want to be able to read code it's best to know a little about both formatting styles (or to know at least where the documentation can be found)
For writing code you can just learn one of them and use it. Most people nowadays seem to prefer the new style, though I prefer for simpler cases still the old style and use the new style rarely / only if it has an added value.
AnB ArwAuthor Commented:
Thank you
All Courses

From novice to tech pro — start learning today.