如何在Python中将分数作为输入,并将分数的值用于算术?

2024-10-06 12:56:27 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我用来说明我的问题的示例代码。如果输入是整数或小数,则按预期工作。但是,如果输入是一个分数,例如4/5,它会抛出一个ValueError,因为4/5是一个无法转换为浮点的字符串

myinput=input("Enter number. ")
doubleofmyinput=float(myinput)*2
print(doubleofmyinput)

当不使用input()时,这不是问题,因为float(4/5)有效,而float(“4/5”)无效,而float(“4.5”)和float(4.5)都有效。谢谢


Tags: 字符串代码示例numberinput整数float分数
3条回答

使用fractions library可以执行以下操作:

import fractions

myinput = input("Enter number. ")
try:
    if not myinput.isnumeric():
        myinput = fractions.Fraction(myinput)
except ValueError:
    throw ValueError(myinput + " is not a number")

doubleofmyinput=float(myinput)*2
print(doubleofmyinput)

你希望在接受意见方面有多慷慨

如果它只是普通分数(或混合分数),您可以有一个特殊情况,使用.split('/')或正则表达式将输入字符串分解为其组成部分,分别转换,然后将它们组合成float、a^{}或a^{}(取决于您需要或可以容忍的舍入行为).

如果您想更普遍地接受任意表达式,最好找一个库来实现这一点;一个快速的谷歌建议simpleeval,但可能还有其他的

如果您只想将值作为分数输入,而不将其显示为分数,那么我建议使用eval

myinput=float(eval(input("Enter number. ")))
doubleofmyinput= myinput *2  
print(doubleofmyinput)

相关问题 更多 >