【问题标题】:How to run the math from an input in python如何从python中的输入运行数学
【发布时间】:2017-02-28 02:28:00
【问题描述】:

我正在用 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)

计算机输出:

(1, '+', 1)

【问题讨论】:

标签: python


【解决方案1】:

虽然eval 在非常一般的上下文中运行,并且引入安全问题的范围很大,但ast.literal_eval 仅用于评估字符串文字,因此范围更窄,因此更安全。

from ast import literal_eval

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(literal_eval(''.join(map(str, vsofar))))

否则,创建从运算符到函数的映射,以查找要为每个运算符调用的函数。

import operator
import sys

ops = {'+': operator.add, 
       '-': operator.sub}

v1 = int(input('enter first num'))

op1 = input('input operator')

if not op1 in ops:
    print('unsupported operation')
    sys.exit(1)

v2 = int(input('enter second num'))

print(ops[op1](v1, v2))

这样做的好处是,您不必在程序逻辑中乱七八糟地添加新的(二进制)操作。您只需将它们添加到 dict 中,在长 if/elif 链中打错字的机会要少得多。

【讨论】:

    【解决方案2】:

    最安全和最简单的方法是使用 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,c 中,该变量将打印在该操作之后的行中。如果所有操作都不起作用,则打印无效语句。

    这是最平淡、最简单、最漫长的方法。但是,eval() 函数使用起来并不安全。 Paul Rooney 的回答比我的方式更短但更复杂。

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      你可以评估!

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

      看看this

      希望这会有所帮助!

      【讨论】:

      • 我刚刚做到了!并且工作正常。我从终端复制粘贴!
      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:
        num1= int(input("first number: "))
        num2= int(input("2md number: "))
        sign= input("sign operator: ")
        
        if sign == '+':
            print("Answer is", num1+num2)
        elif sign == '-':
            print("Answer is", num1-num2)
        elif sign == '*':`enter code here
            print("Answer is", num1*num2)
        elif sign == '/':
            print("Answer is", num1/num2)
        else:
            print("am not built to use this sign yet")
        

        【讨论】:

          猜你喜欢
          • 2018-12-13
          • 2018-09-12
          • 1970-01-01
          • 2020-01-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-13
          相关资源
          最近更新 更多