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.

Thanks
AB
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


or

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
> https://docs.python.org/3/library/stdtypes.html#old-string-formatting

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 https://docs.python.org/3/library/stdtypes.html#str.format , which is more powerful, but sometimes for simple cases 'just' more characters to type.
New style formats look like
format_string.format(formatarguments)

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.
0
 
AnB ArwAuthor Commented:
Thank you
0
All Courses

From novice to tech pro — start learning today.