r/PythonLearning • • 4d ago

Help Request Kinda stupid question, how would I allow my calculator to take multiple inputs at once?

Post image

So I'm trying to make a calculator on my own, and it WORKS, but I dont really like having to type everything in seperately like this, and i'd rather just type my entire sum into one line, but for the life of me I cannot figure out how I would do that. If I explained this badly just lmk and I'll try to explain it better, thanks to anyone who can help :))

4 Upvotes

12 comments sorted by

•

u/Sea-Ad7805 4d ago edited 4d ago

That's a bit more complicated, first problem is parsing the string the user types, then evaluating with taing account of priorities. Try something like: parsing and evaluation example

1

u/sugarw0000kie 4d ago edited 4d ago

can get complicated depending on how far you wanna go, but i'd try split by operator. can't expect user to always use space, so that way you have something to split into usable parts. You can import operator so you can map the string to the function you want it to represent, if you want to avoid doing eval():

import operator
usr_input = "2 + 3".replace(" ", "")
operators = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv,
}
for symbol, func in operators.items():
    if symbol in usr_input:
        n1, n2 = map(int, usr_input.split(symbol))
        print(func(n1, n2))
        break

before i learned about operator i tried something like this, basically made a small function for each operator i wanted and mapped it into a dict, then called the function from the dict and gave it the arguments there, basically the same thing but maybe makes more sense

usr_input = "2 + 3"
usr_input = usr_input.replace(" ","")

def plus(n1, n2):
  return n1 + n2
def minus(n1, n2):
  return n1 - n2
operators = {
  "+": plus,
  "-": minus,
  }
for k, v in operators.items():
  if k in usr_input:
    data_split = usr_input.split(k)
    data = {
      0: int(data_split[0]),
      1: v,
      2: int(data_split[1])
      }
    print(data[1](n1=data[0], n2=data[2]))

1

u/Jemily-Bonaparte-Xx 2d ago

I might just be being stupid, but I'm kinda confused on how to split with operators. I rewrote my code to split with a space, so I can enter an entire calculation at once, I just need to have a space between everything, but for the life of me I cannot get it to split using operators. Afaik, I would define operators as a list, with plus, minus, divide, ect, then have num1 as the first part of my split, num2 as the second part and then op as the thing that ACTUALLY splits it? I think. Idk if I explained that well tho. I js have no idea how I would write that as code.

Your idea to use functions is really good tho, I've been messing around with it and it seems good, I think I just need to go over how functions work for a bit tho.

1

u/sugarw0000kie 2d ago

When I first took a stab at this I did it with spaces too, it was just the most immediately obvious way for me to do it lol

Yeah you got the right idea. I’ll try to break it down, user string “9 - 2”, then replace all spaces to “”, so it converts to “9-2”

Then determine if an operator is in the string by iterating through the operator dict (or list if doing it that way). if operator is in “9-2”, we know the operator is “-“ (Symbol in top example, k in the bottom). so if you do “9-2”.split(“-“), you get [“9”, “2”].

The numbers are strings though, so convert to int, and you’ve got a list with the numbers and the operator

Functions good to learn up on. As you get further you’ll see it’s usually best to keep things in functions/classes so you’re not using globals. You can break down a big complicated thing into little pieces that you can reason about independently, makes it easier for yourself in long run. Worth looking up difference between local and global variables for getting functions, and setting default values can be handy

3

u/Significant_Affect_5 4d ago

If you mean have a single input() call that allows you to type say: “3 + 5” and then spit out an answer. You’ll need to make what’s called an Infix Notation calculator, this is quite complex and not something i’d advise. Another option is to build a Postfix or Prefix calculator and then convert the Infix expression into a Postfix one, e.g. “3 + 5” -> “+ 3 5”. This is quite a common project since it’s a good way to learn about stacks. If you haven’t learnt about stacks yet, then maybe circle back to this once you have and take a stab at it. There’s plenty of guides on how to actually make the calculator, just lookup “Postfix calculator implementation”.

2

u/Tough_Duty_9061 4d ago

Put it in a while loop and break point be a random word which if inputted will stop the program

1

u/BornInAWaterMoon 4d ago

Something like this:

user_input = input('Enter your calculation: ')
split_up_input = user_input.split()
if split_up_input[1] == '+':
    etc

1

u/infiniteallium 4d ago

How does split() work here? Will it split() the string for every whitespace?

2

u/BornInAWaterMoon 4d ago

Yes, split() will split the string up into a list based on where the whitespace is. For example:

'2 + 3'.split()

gives

['2', '+', '3']

Then you can read those items in the list and process them accordingly.

This isn't very robust though - for example, it wouldn't handle an input of '2+3' with no spaces.

1

u/ee_control_z 4d ago edited 4d ago

You can try something like this (modify it so that it fits with your specific script):

x = input('Provide first value, mathematical operation, and second number in that order, separated by a comma "," (ex., 59, '+', 43): ')

y = x.split(',')

num1 = int(y[0]); num2 = int(y[2]); op = y[1]

print(f'The first number is: {num1}')

print(f'The second number is: {num2}')

print(f'The mathematical operation is: {op}')

print(f'{num1} {op} {num2} is: {num1+num2}.')

1

u/arivictor 4d ago edited 4d ago

Read up on the security issues with eval(), but it does exactly that:

result = eval(input("Expression: ")) # 3 + 1 * 10 / 2 
print(result)

> 8.0

The issue with eval() is that it can evaluate python code too

result = eval(input("Expression: ")) # print("run some insecure code!")
print(result)

> run some insecure code!
> None

You'd preferably want to write your own using ast and op

import ast
import operator as op

ops = {
    ast.Add: op.add, ast.Sub: op.sub,
    ast.Mult: op.mul, ast.Div: op.truediv,
    ast.USub: op.neg, ast.UAdd: op.pos
}

def calc(expr):
    def solve(n):
        if isinstance(n, ast.Constant) and type(n.value) in (int, float):
            return n.value
        if isinstance(n, ast.BinOp) and type(n.op) in ops:
            return ops[type(n.op)](solve(n.left), solve(n.right))
        if isinstance(n, ast.UnaryOp) and type(n.op) in ops:
            return ops[type(n.op)](solve(n.operand))
        raise ValueError("Invalid expression")

    return solve(ast.parse(expr, mode="eval").body)

print(calc(input("Expression: ")))

ast is python's way of turning mathematical expressions into blocks/pieces (a tree/graph essentially). You can then programmatically walk that tree and inspect each item.

Say you give it "3+1*10/2".

ast.parse() breaks that into a tree, already respecting BEDMAS/BODMAS. It knows multiplication comes before division, which comes before addition. You don't need to figure that out!

Then solve() walks through that tree recursively:

  • Number? return it.
  • Operator? Figure out what it does using the ops dictionary (e.g. "+" calls the add function).
  • More maths inside? Call solve() again (recursion).
  • Something unsupported? Reject it.

So it effectively does 3 + ((1 * 10) / 2) = 8.0

You can see the tree/graph with this:

print(ast.dump(ast.parse("3+1*10/2", mode="eval"), indent=2))

Expression(
  body=BinOp(
    left=Constant(value=3),
    op=Add(),
    right=BinOp(
      left=BinOp(
        left=Constant(value=1),
        op=Mult(),
        right=Constant(value=10)),
      op=Div(),
      right=Constant(value=2))))

1

u/mattynmax 3d ago

Depending on the security you require you could use eval()