如何从python中的输入运行数学

2024-10-01 13:36:14 发布

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

我正在用python创建一个游戏,在那里我需要运行基本的数学运算。这些操作将由用户作为输入提供。我该怎么做?在

到目前为止,每个数字和每个运算符都有独立的变量,但是,当我运行代码时,它不将运算符('+','-','*','/')识别为运算符,而是将其识别为字符串。因此,当运行编程时,它将作为1'+'1运行。在

print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)

vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)

vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)

vsofar = (vinput1, vop1, vinput2)
print(vsofar)

计算机输出:

^{pr2}$

Tags: thenumberinputisas运算符operatorint
3条回答

你可以评估!在

>>> input1=1
>>> input2=3
>>> vop1="+"
>>> print eval(str(input1)+vop1+str(input2))
4

看看this

希望这有帮助!在

最安全、最简单的方法是使用if语句检查输入的符号。if语句示例如下:

print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)
vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)
vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)

if (vop1 == "-"):
    vsofar = vinput1 - vinput2
    print(vsofar)
elif (vop1 == "+"):
    vsofar = vinput1 + vinput2
    print(vsofar)
elif (vop1 == "/"):
    vsofar = vinput1 / vinput2
    print(vsofar)
elif (vop1 == "*"):
    vsofar = vinput1 * vinput2
    print(vsofar)
else
    print("Invalid operator entered.")

为了快速解释,这些if语句检查输入的运算符(存储在vop1中)是否与-、+、*或/运算符匹配。如果它与其中任何一个匹配,则执行其相应的操作并将其存储在变量vsofar,cwh在该操作之后的行中打印。如果这些操作都不起作用,那么将打印一条无效语句。在

这是最平淡、最简单、也有点漫长的方法。但是,eval()函数使用起来不安全。保罗·鲁尼的答案是,一个比我的方式更短但更复杂的方法。在

希望这有帮助!在

如果不想使用eval(),可以尝试一系列条件语句来测试运算符,然后在此基础上执行正确的计算。在

if vop1 == "+":
    return vinput1 + vinput2
if vop1 == "-":
    return vinput1 - vinput2

相关问题 更多 >