Python Forum
Converting str to int or float
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting str to int or float
#5
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Converting str to int or float - by juliabrushett - Jun-16-2018, 06:53 PM
RE: Converting str to int or float - by ichabod801 - Jun-16-2018, 07:06 PM
RE: Converting str to int or float - by ljmetzger - Jun-17-2018, 09:57 AM
RE: Converting str to int or float - by volcano63 - Jun-17-2018, 03:05 PM
RE: Converting str to int or float - by DeaD_EyE - Jun-17-2018, 06:28 PM
RE: Converting str to int or float - by volcano63 - Jun-17-2018, 08:08 PM
RE: Converting str to int or float - by DeaD_EyE - Jun-18-2018, 10:08 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020