Hello I'm newbie in python and I wanted to know if I can create a function that only accepts certain types of values, in this case string, else error
parameter that needs to be string
|
v
def isfloat(a):
if a.count('.') > 1:
return False
for c in a:
if c.isnumeric() or c == '.':
v = True
else:
return False
return v
In Python 3.5+ you can use typing to annotate your function:
def isfloat(a: str):
# More code here...
But type annotation doesn't actually check types!
So, it's better to add robust type check with assert statement:
def isfloat(a: str):
assert isinstance(a, str), 'Strings only!'
# More code here...
With assert
your function will raise AssertationError
if a
is not a string.
You could enclose your code within an if statement such as the following.
def enumerico(a):
if (isinstance(a, str)):
<your code>
else:
<throw exception or exit function>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With