Python Forum

Full Version: Converting str to int or float
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
My assignment is to take in an expression(such as 4 + 5), then calculate. I am to use the .split() function to separate parts of the statement. I think my program should work, I am having trouble converting my split expression into an int or float so the numbers can be used for calculation.

Thanks in advance for your help!

'''
Name: Julia Brushett
ID#: 0532966
Date: June 16, 2018
Description: Assignment 6
'''

expression = str(input("Enter an expression for me to calculate: "))

expression = expression.split()

op = expression[1]
num1 = expression[0]
num2 = expression[2]


if (op == '+'):
    print("The sum is", num1 + num2)
elif (op == '-'):
    print("The difference is", num1 - num2)
elif (op == '*'):
    print("The product is", num1 * num2)
elif (op == '/'):
    if (num2 == 0):
        print("The quotient is", num1 / num2)
    else:
        print("Cannot divide by 0")
else:
    print("Invalid input")
The int built-in will convert a string representing an integer into an actual integer.

>>> x = '5'
>>> x
'5'
>>> int(x)
5
>>> int(x) + 3
8
Note that it will raise an error if the string cannot be converted to an int. I don't know if your teacher expects you to be able to handle that.
As you already found out, split() parses the values in strings. So 3 + 4 is really string concatenation and gives a result of 34.

For extra credit you could:
a. Check to make sure you have exactly 3 items in the expression len(expression).
b. Assuming you are working with integers only, you could check that num1 and num2 are numbers (e.g. num1.isdigit()).
c. Checking for 'float' is probably beyond the scope of this exercise. The following working code is probably for future reference in combining float and int:
def get_int_or_float(v):
    # NOTE: '1.0' will be identified as type 'int'
    try:
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        if number_as_float == number_as_int:
            return number_as_int
        else :
            return number_as_float
    except:
        return v

num1 = '1'
num1 = get_int_or_float(num1)
print(num1, type(num1))

num1 = '1a'
num1 = get_int_or_float(num1)
print(num1, type(num1))


num1 = '1.1'
num1 = get_int_or_float(num1)
print(num1, type(num1))

num2 = 3.3

if isinstance(num1, str) or isinstance(num2, str):
    # this would be the error branch
    print("string")
else:
    # this would be the calculation branch - exactly as you have it
    print("int or float or combination of both")

Output:
1 <class 'int'> 1a <class 'str'> 1.1 <class 'float'> int or float or combination of both
Lewis
Please, note
num1, op, num2 = expression.split()
is more Pythonic way to assign expression operators
Instead of branching with if-conditions, you can use a dict, to get the right operator-function for the operator.

import operator


operators = {
    '+': operator.add,
    '-': operator.sub,
    '/': operator.truediv,
    ':': operator.truediv,
    '*': operator.mul,
    }
Values can be also functions. Python hast first class functions, which means you can even
give a function as an argument to another function or use fuctions as keys/values and
you can even put functions in functions (closures).

Accessing a key for the operators dict:
op = '+'
operator_function = operators[op]
result = operator_function(1, 41)
print('Operator:', op)
print('Function:', operator_function)
print('Result:', result)
Accessing a Key, which does not exist, raises a KeyError.
op = '!'
operators[op]
Error:
<ipython-input-8-b9b89a1eccb0> in <module>() 1 op = '!' ----> 2 operators[op] KeyError: '!'
A ValueError raises, when a conversion is not possible: int('abc'), int('1.5')
A ValueError raises also, when you want to unpack Values from an iterable e.g. list,
but too less/much values are available to assign them to the names on the left side.

The last Exception you should know is TypeError.
In general a TypeError raises, when there is an illegal operation like
addition of a integer with a string. Python has a very good type safety.

The Exception ZeroDivisionError needs no explanation, but it's also interesting for a calculator.

You can use try...except... to catch errors. In Python we follow the principle:
Don’t Ask For Permission. Ask For Forgiveness.

A very easy example is the conversion to float.
Following values are valid:
  • 1
  • 1.
  • .1
  • .1E-12
  • 1.1E+12
  • +1.5e+22
  • -.1e-1

The programmers first mind is: "Yay, let's do regex"
After a while the programmer comes back and asks the question on StackOverflow,
how to parse with regex a number.
One of the answer could be: "Then you have 2 Problems, the original task and regex"
But there was one guy, who came up with error catching. The implementation of float()
is perfect. The function know how to parse a string and convert it right. It's used every
day and is very well tested. So just use the float function to convert strings to float
and when it fails, you know the string was not a float.

Code:
try:
    expression = input('Enter an expression for me to calculate: ')
    val1, op, val2 = expression.split()
    num1, num2 = int(val1), int(val2)
    # ValueError if the conversion of val1 or val2 was not succsessful 
    # ValueError if too much or not enough values to unpack
    operator_function = operators[op]
    # KeyError if the Key does not exists in the dict
except ValueError:
    print('Invalid expression:', expression)
except KeyError:
    print('Unknown operator:', op)
else:
    print('Result:', operator_function(num1, num2))
All posted code examples here (inclusive mine) can not parse expressions like this one: 1+1.
If you want to do this, you can use regex, but only for splitting the values from operator.
(Jun-17-2018, 06:28 PM)DeaD_EyE Wrote: [ -> ]Instead of branching with if-conditions, you can use a dict, to get the right operator-function for the operator.

I couldn't agree more - but

(Jun-16-2018, 06:53 PM)juliabrushett Wrote: [ -> ]Description: Assignment 6
The opinions can be very different. I guess here counts only one opinion and this is the teachers opinion how the students should solve the task. I've seen that very often they should solve simple tasks without using parts of Python. By the way: Setting a Value in a dict, is an assignment.