1

I have been recently working on code that is a calculator. I know calculations can be done in the shell but that's no fun. Anyway, I have successfully been able to separate the numbers from the equation so that I can add them together. However it outputs like so:

Numbers: 22

This happens with the equation 2+2.

What I want to happen is it to take this integer (22) and separate it into 2 and 2 then assign those to variables "num1" and "num2" so that I can add them.

I have already tried:

[int(i) for i in str(Numbers)]

But the output is in a list and I have not found anything about taking a list item and assigning it to a variable.

I have looked at this: Splitting integer in Python?

That is what got me my output above. I have also looked at this: Getting only element from a single-element list in Python?

But I didn't understand that and don't have a high enough reputation score to comment and ask for explanation.

This is my current code as it currently stands:

var = input("Type equation:")

if " + " in var:
    nums = str(re.findall(r'\d',var))
    nums2 = nums.replace("['", "")
    nums3 = nums2.replace("', '", "")
    Numbers = nums3.replace("']", "")
    print(Numbers)
Char Gamer
  • 41
  • 7

2 Answers2

1

But the output is in a list and I have not found anything about taking a list item and assigning it to a variable.

Use access through index:

num1, num2 = [int(i) for i in str(Numbers)] [0], [int(i) for i in str(Numbers)] [1] 
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
  • 1
    This redoes the same operation twice unnecessarily. Storing the result or using unpacking is a better idea. – iz_ Mar 28 '19 at 04:21
  • Yes, to optimize that he can populate the list into a local variable and later access through index. – Saurav Sahu Mar 28 '19 at 04:22
  • 1
    To simplify the code, simply do `num1, num2 = (int(i) for i in str(Numbers))`. – iz_ Mar 28 '19 at 04:26
0

Assign your output to two variables num1, num2

num1,num2=list(str(Numbers))

Sandy
  • 133
  • 8
  • 1
    You don't need the `list(str())`, `str()` is enough, i.e. `num1, num2 = str(Numbers)`. However, they will be strings, not integers. – iz_ Mar 28 '19 at 04:20