4

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
3
  • If you want to know whether a is str,you can use isinstance(a,str). Commented Mar 19, 2020 at 13:24
  • 1
    if not isinstance(argument, str): raise ValueError('argument has to be a string') Commented Mar 19, 2020 at 13:25
  • Instead of image, Always add your code so that we can test it instead of rewriting it again. Commented Mar 19, 2020 at 13:43

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

Note that type(a) is str returns False if a is an instance of a str subclass. isinstance(a, str) is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.