jshzglr
jshzglr

Reputation: 23

Rendering number to n variable places

Attempting to print pi rendered to inputted decimal places using {:.Nf}

Tried replacing variable N with inputted variable n. Also replacing N with {} and assigning n to that. Also replacing n with {n}.

I'm sure the answer is obvious but I can't seem to see it.

from math import pi

# Example input() statement
n = int(input('Please enter an integer: '))

format_string = '{:.nf}'

# Replace this with your own print statement
print(format_string.format(pi))

Expecting pi to n decimal places, yet it is returning:

"ValueError: format specifier missing precision"

which I assume means variable format_string is not formatted correctly.

Upvotes: 2

Views: 98

Answers (2)

Tomerikoo
Tomerikoo

Reputation: 19414

As to your error, it is because n is not a valid format-specifier. Of course python can't know you mean your local variable n, so you have to tell it that. To keep your code in the same structure, you will need 2-level formatting. Something like:

>>> format_string = '{{:.{n}f}}'.format(n=n)
>>> print(format_string.format(pi))
3.14159265

Or simply:

>>> format_string = '{:.{n}f}'
>>> print(format_string.format(pi, n=n))
3.14159265

I would personnaly get rid of the seperate format variable and use it directly as one string in the print.

for n = 8:

  1. using f-strings: (Python version >= 3.6)
>>> print(f"{pi:.{n}f}")
3.14159265
  1. using format: (Python version >= 2.6)
>>> print("{pi:.{n}f}".format(pi=pi, n=n))
3.14159265
  1. using old % formatting:
>>> print("%.*f" % (n, pi))
3.14159265

Upvotes: 0

Rory Daulton
Rory Daulton

Reputation: 22544

One way to get the variable n into the format string is to use an f-string, which was introduced in Python 3.6. The f-string allows n to be replaced with its current value. However, this requires braces, and the braces that you currently have in your code will also be interpreted as wanting to replace a variable. So replace those braces with doubled braces.

from math import pi

# Example input() statement
n = int(input('Please enter an integer: '))

format_string = f'{{:.{n}f}}'

# Replace this with your own print statement
print(format_string.format(pi))

When I run this and input the value 10, I get the printout

3.1415926536

If you are running a version of Python before 3.6, let me know and I'll show you how to use the format method of strings to get the same effect.

Upvotes: 1

Related Questions