使用字符串格式化规范控制小数精度:f-string变量报错原因与修复
错误原因与修复方案
为什么会触发ValueError?
f-string中指定小数精度的格式符(比如.2f里的2)要求必须是整数,但你的代码里precision是float类型(通过float(input(...))得到)。把浮点数代入格式指定符的位置,Python无法识别,就会抛出Invalid format specifier错误。
修复代码
直接将precision转换为整数即可,因为小数位数只能是整数:
from math import pi precision = int(input("Enter digits of decimals:")) print(f'The value of pi to {precision} digits is: {pi:.{precision}f}')
可选优化:输入验证
如果要避免用户输入非整数或负数导致的错误,可以加简单的输入校验:
from math import pi while True: try: precision = int(input("Enter digits of decimals:")) if precision >= 0: break print("Please enter a non-negative integer.") except ValueError: print("Please enter a valid integer.") print(f'The value of pi to {precision} digits is: {pi:.{precision}f}')
内容的提问来源于stack exchange,提问作者Nebneb 5
相关产品推荐
相关产品推荐

