一行,三个变量

Sti*_*lid 6 python

我在这里试图在python中创建一个简单的计算器,我想知道是否有可能在命令运行时将3个第一行放入一行.我的意思是; 我不必按Enter键键入下一个数字/运算符,而是按空格键(在输入部分).

while True:
    import operator

    num1 = int(input("Whats the first number:"))
    oper = input("Which operator would you like to use: (+,-,/,*,**,^)  :")
    num2 = int(input("Whats the second number:"))


    if oper == "+":
        x = operator.add

    elif oper == "-":
        x = operator.sub

    elif oper == "*":
        x = operator.mul

    elif oper == "/":
        x = operator.__truediv__
    elif oper == "**":
        x = operator.pow
    elif oper == "^":
        x = operator.xor

    else:
        print("invalid input")

    print(num1,oper,num2,"=",x(num1,num2))
Run Code Online (Sandbox Code Playgroud)

Ror*_*ton 8

您可以使用splitPython字符串的方法来完成此任务.请注意,此代码取决于输入的三个以空格分隔的对象.如果输入更多或更少或忘记空格,或者"数字"实际上不是整数,则会出错.

print("Enter a number, a space, an operator, a space, and another number.")
num1str, oper, num2str = input().split()
num1, num2 = int(num1str), int(num2str)
Run Code Online (Sandbox Code Playgroud)