python - 使用 float 创建 if 语句

标签 python python-3.x if-statement floating-point

我正在尝试创建一个转换程序,自动将转换后的文本复制到 Windows 剪贴板。我试图做到这一点,以便如果用户输入一个保留到小数点后 2 位或更少的数字,它会将转换后的结果复制到剪贴板的 3 位。如果用户输入一个精确到小数点后 3 位或更多的数字,则它将转换后的结果复制到精确到小数点后 4 位的剪贴板。当我运行代码时,我收到一个 ValueError 但我不明白为什么。这是我收到的错误

line 88, in con
  if float_number >= ("%.3f" % float_number):
ValueError: incomplete format

这是给我带来麻烦的代码部分(我添加了注释来解释你们可能缺少的内容)

def con():
    While True:
        print("Return = Main Menu, Surface = RA Conversion")
        print(MM_break) #This is defined globally elsewhere
        number = (input())
        if number in('Return', 'return'):
            break
        elif number in('Surface', 'surface'):
            surf() #I have a def surf() elsewhere in the program
        elif number in('help', 'Help'):
            help() #I have a def for help() elsewhere
        elif number in('end', 'exit', 'quit')
            break
        else:
             try:
                 float(number)
             except ValueError:
                 print(sys_Error) #I have a global variable for sys_Error elsewhere
                 break
             else:
                 float_number = float(number)
             Convert = float_number/Inches
             Results_3 = ("%.3f" % Convert)#converts 3 decimals
             Results_4 = ("%.4f" % Convert)#converts to 4 decimals
             print(line_break)
                 print(" ")
             print('\t', Results_3)
             print('\t', Results_4)
             print(line_break)
             print(" ")
             if float_number >= ("%.3f%" % float_number):
                 r = Tk()
                 r.withdraw()
                 r.clipboard_clear()
                 r.clipboard_append(Results_4)#appends Results_4 to clipboard
             else:
                 r = Tk()
                 r.withdraw()
                 r.clipboard_clear()
                 r.clipboard_append(Results_3)

最佳答案

您的错误表明您的字符串模板中有错误,您缺少 %:

if float_number >= (".3f" % float_number):

应该是

if float_number >= ("%.3f" % float_number):

然而,现在您正在尝试将 float 值与字符串进行比较:

if float_number >= ("%.3f" % float_number):

这将抛出一个TypeError:

>>> 0.123 >= '0.123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: float() >= str()

不要那样做。比较 float 与 float ,使用round()创建舍入值:

if float_number >= round(float_number, 3):

关于python - 使用 float 创建 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16339900/

相关文章:

python - 如何强制除法为 float ?除法不断四舍五入为0?

python - 来自 scikits cross_val_score 的所有类别的 f1 分数

python - 基本授权凭证不会出现在 Scapy 中?

python - 什么是嵌套循环,如何在下面的示例中使用它?

Python Flask - WTF SelectField 数据导致错误 _mysql_exceptions.ProgrammingError

android - 所有屏幕的 GUI 显示布局相同 Kivy

python - FileNotFoundError : [Errno2]: No Such file or directory:

java - 多个 if 语句

java - 扫描仪在 if 语句中不起作用

python - 如何在神经网络模型中使用 tensorflow session