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))
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With