How to add two numbers inside string like that "25 + 30"

Tell us what’s happening:
Describe your issue in detail here.

Your code so far

def Add_Two_No(Mylist):
    for item in Mylist:
        x = item.split()
        print(int(x[0]) + x[1] + int(x[2]))
Add_Two_No(["325 + 1025", "2055 - 100"])

this code make the error : unsupported operand type(s) for +: ‘int’ and ‘str’

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 OPR/74.0.3911.160

Challenge: Arithmetic Formatter

Link to the challenge:

This means that you cannot add a number and a string.

Your calculation right now is:
325 + '+' + 1025

Looks weird, doesn’t it?

how i can solve this problem

Note : we aren’t here to write the code for you.

You need to add when there is a + and subtract when there is a -. That sounds like some conditional logic.

1 Like

thanks for you but what is the idea of a solution?

The idea is that you use conditional logic to add when there is a + in the problem and subtract when there is a - in the problem?

1 Like

Now its ok thanks for you

def Add_Two_No(Mylist):
    for item in Mylist:
        x = item.split()
        if x[1] == '+':
            print(int(x[0]) + int(x[2]))
        if x[1] == '-':
            print(int(x[0]) - int(x[2]))
Add_Two_No(["325 + 1025", "2055 - 100"])
1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

thanks for you

An other solution

def Add_Two_No(Mylist):
    for item in Mylist:
        print(eval(item))
Add_Two_No(["325 + 1025", "2055 - 100", "12 * 15"])

While this does work, keep in mind eval() will try to parse any string as Python code and thus poses a significant security-risk.

1 Like

I know that function (eval()) deals with multi math operation in one string
like this ( “5 + 8 - 3 * 2”)

Not exactly - it will read a string and try to parse it as if it was written in Python code. Ofcourse if you write a calculation you could write in Python, it will parse it.
However if you write another command - it will ALSO parse it.
eval("print('This is inside eval()')") will also be executed as a print command. And if I put some insanely massive list-comprehension there, I can completly overwhelm your computer. As in, I literally wrote list comprehension that forced me to do a hard resett of my computer.