Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line, three variables

Tags:

python

I am here trying to just make a simple calculator in python, and I wonder if its possible to make the 3 first lines in to one line when command run. What I mean with that is; I don't have to press enter to type the next number/operator but press space instead (in the input section).

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))
like image 219
Stian Breilid Avatar asked Feb 10 '19 00:02

Stian Breilid


People also ask

How do I make multiple variables in one line Python?

Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator.


1 Answers

You can use the split method of Python strings to accomplish this. Note that this code depends on three objects, separated by spaces, being entered. If more or fewer are entered or the spaces are forgotten, or either "number" is not actually an integer, there will be an error.

print("Enter a number, a space, an operator, a space, and another number.")
num1str, oper, num2str = input().split()
num1, num2 = int(num1str), int(num2str)
like image 70
Rory Daulton Avatar answered Sep 17 '22 22:09

Rory Daulton