-2

How do I allow the user to input values and receive the answer, whilst keeping the values of "x + xy + y" on one line?

print("Calculator")

x = input("")
xy = input("")
y = input("")

if xy == "+":
    print(x+y)
elif xy == "-":
    print(x-y)
elif xy == "*":
   print(x*y)
elif xy == "/":
    print(x/y)
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 1
    Use only one `input` and then use a regex or similar to parse the string. Also, do you want the user to hit Enter between x, xy, and y? – tobias_k Aug 23 '16 at 12:02
  • 1
    This code probably is not doing what you expect in anyway as you're not converting the strings, i.e: 1 + 2 = 12 – dfranca Aug 23 '16 at 12:02
  • Possible duplicate of [Python creating a calculator](http://stackoverflow.com/questions/13116167/python-creating-a-calculator) – log0 Aug 23 '16 at 12:16
  • I changed the code. I only want enter for the end result @tobias_k – Michael Thin Aug 23 '16 at 22:39
  • I reverted this to the previous version. Please do not just replace your question with an entirely different one, thus invalidating all existing answers. If you have a follow-up question, post it as another question. – tobias_k Aug 24 '16 at 09:46

3 Answers3

1

I'd suggest using a single input statement and then using a simple regular expression to parse the string into x, y and the operator. For example, this pattern: (\d+)\s*([-+*/])\s*(\d+). Here, \d+ means "one or more digits", \s* means "zero or more spaces", and [-+*/] means "any of those four symbols. The parts within (...) can later be extracted.

import re
expr = input()  # get one input for entire line
m = re.match(r"(\d+)\s*([-+*/])\s*(\d+)", expr)  # match expression
if m:  # check whether we have a match
    x, op, y = m.groups()  # get the stuff within pairs of (...)
    x, y = int(x), int(y)  # don't forget to cast to int!
    if op == "+":
        print(x + y)
    elif ...:  # check operators -, *, /
        ...
else:
    print("Invalid expression") 

Alternatively to four if/elif, you could also create a dictionary, mapping operator symbols to functions:

operators = {"+": lambda n, m: n + m}

And then just get the right function from that dict and apply it to the operands:

    print(operators[op](x, y))
tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

Here's another possibility.

raw = raw_input("Calculator: ")
raw1 = raw.split(" ")
x = int(raw1[0])
xy = raw1[1]
y = int(raw1[2])

if xy == "+":
    print raw, "=", x + y 
elif xy == "-":
    print raw, "=", x-y
elif xy == "/":
    print raw, "=", x/y
elif xy == "*":
    print raw, "=", x*y
Daniel Lee
  • 7,189
  • 2
  • 26
  • 44
0

You can get input like this:

cal = input("Calculator: ").strip().split()
x, xy, y = int(cal[0]), cal[1], int(cal[2])

Then you can process your input data.

Rafiqul Hasan
  • 488
  • 4
  • 12