1
base = input('What is the base?: ')
if '.' in base:
    base = float(base)
else:
    base = int(base)

Hello, what I was trying to do is to convert the string into either a float() or int() depending on what the user inputs. This is for a math formula, but I'm wondering if there is any other way to write the code.

Aurick
  • 11
  • 1
  • 1
  • what's wrong with that? Clean/quick – samman Jul 09 '20 at 19:11
  • @samman: Well, one issue is that it won't accept legal float literals like `4e10`. The usual rule is "just try the conversion, catch the exception if it fails", because it's really hard and pointless to try to cover all the legal options, and the constructor already *is* a validity checker. The duplicate I linked has a top answer using EAFP properly. – ShadowRanger Jul 09 '20 at 19:13
  • Oh, misread the question, thought they were just asking how to convert a string to a float/int in general. – samman Jul 09 '20 at 19:16
  • I would have used a loop (`for func in [int, float]:`) but otherwise the answer for the duplicate is OK. – Matthias Jul 09 '20 at 19:16

0 Answers0