0
# function that prints hello your name is x and you are y years old
# name must be of type string and cannot be empty
# age must be of type int and cannot be 0
def functionX(name, age):
    if name == "":
        raise ValueError("name cannot be empty")
    if not isinstance(name, str):
        raise TypeError("name seem not to be a string")
    if age == 0:
        raise ValueError("age cannot be 0 (zero)")
    if not isinstance(age, int):
        raise TypeError("age needs to be an integer")
    print("hello ", name, ", you seem to be ", age," years old")

Is this a correct way of checking parameters provided to a function?

4
  • 2
    Yes those assertions meet the requirements in your code. Commented Aug 12, 2021 at 19:19
  • 2
    Use a TypeError for the isinstance() checks. ValueError is for the correct type but incorrect value Commented Aug 12, 2021 at 19:19
  • 1
    You could add type hints and use mypy to perform a static analysis. Commented Aug 12, 2021 at 19:19
  • The code is fine; the constraints themselves aren't common in idiomatic Python. The print call will only care that str(name) and str(age) don't raise exceptions. The empty string and 0 can both be printed just fine. Commented Aug 12, 2021 at 19:41

1 Answer 1

1

Making the code "cleaner" - adding type hints and using f string. Using a type checker like mypy will verify that the function caller is passing a string and an int.

def say_hello(name: str, age: int) -> None:
    if not isinstance(name, str):
        raise TypeError("name seem not to be a string")
    if not name:
        raise ValueError("name cannot be empty")
    if not isinstance(age, int):
        raise ValueError("age needs to be an integer")
    if age == 0:
        raise ValueError("age cannot be 0 (zero)")
    print(f'Hello {name} you seem to be {age} years old')


say_hello('jack', 12)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.