2

So I have a simple program in Python 3 that is just a basic calculator. here is a section of code:

calculation = input("What calculation do you want to do?\n")
if "+" in calculation:
    numbers = calculation.split("+")
    answer = int(numbers[0]) + int(numbers[1])

I have some other operations setup below it. The issue is that if someone was to input anything as well as the operation (e.g. 10++2 or 10+abc2), the code throws back an error because it obviously can't add 10 to abc2.

I thought that I could solve the issue by testing for each individual character but surely that is a long way around the issue. Is there a way to solve the issue using Python?

Cyphase
  • 11,502
  • 2
  • 31
  • 32

4 Answers4

5

Check if both sides are made of digits by the string.isdigit() method:

if numbers[0].isdigit() and numbers[1].isdigit():
     answer = int(numbers[0]) + int(numbers[1])

If you want to go further with your calculator, you should worry about learning regex and parsing.

Assem
  • 11,574
  • 5
  • 59
  • 97
  • This will fail for `2.0` etc.. which is a valid number – Padraic Cunningham Aug 16 '15 at 11:53
  • I understood that OP is just starting a basic calculator that perform `int+int`. I updated the answer to refer that he should go with parsing and regex for more complicated operations. – Assem Aug 16 '15 at 12:02
3

Python, you love it too?

s = ''.join(filter(lambda x: x.isdigit() or x=='+', list(s)))
xrisk
  • 3,790
  • 22
  • 45
  • 1
    The author wanted to throw error in case there is invalid character, but ```filter``` will just ignore invalid parts. I'd use ```if not all(lambda x: x.isdigit() or x=='+', s)``` if I wanted to make sure the input is valid. Also note that there is no need to convert ```s``` to ```list```, as ```str``` is iterable – tmrlvi Aug 16 '15 at 11:35
  • @tmrlvi feel free to suggest an edit! I’m just a beginner in python. – xrisk Aug 16 '15 at 11:37
1

Try this:

calculation = "5+4+3.5"

numbers = calculation.split("+")
numbers2 = []

for num in numbers:
    try:
        numbers2.append(float(num))
    except:
        print("incorrect input")

print(sum(numbers2))
0

You could use a regex to get the digits:

s = "10++abc2.0"

import re
if "+" in s:
    print(sum(map(float,re.findall("\d+|\d+\.\d+", s))))

12.0

If you want to ignore abc2.0 and catch negative numbers, try casting with a try/except:

def parse(s, sign):
    spl = s.split(sign)
    sm = 0
    for i in spl:
        try:
            print(i)
            sm += float(i)
        except ValueError:
            pass
    return sm

sm = parse(s, "+")
print(sm)
10.0

You have to also consider negative numbers but there are cases where you could have + and - in the string so you also need to decide what do do then:

s = "10++abc2.0+-2"
sm = parse(s,"+")
print(sm)
8.0
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321