Home > Back-end >  How to specify the class of arguments for a function?
How to specify the class of arguments for a function?

Time:01-10

I want to create a function which outputs the maximum of three numbers. How do I specify that the arguments of this function are numbers?

a, b, c in range(1000)

def max_ofthree(a, b, c):
    if a >= b and c:
        print(a)
    if b>= a and c:
        print(b)
    if c>= a and b:
        print(c)

max_ofthree(3, 2, 1)

CodePudding user response:

Python is gradually typed. The hints do not affect the behaviour of the program. However, you can use mypy for type checking.

Adhering to PEP 484:

this PEP proposes a straightforward shortcut that is almost as effective: when an argument is annotated as having type float, an argument of type int is acceptable

def max_of_three(a: float, b: float, c: float) -> float:
    _max = a
    _max = b if b > _max else _max
    _max = c if c > _max else _max
    return _max

CodePudding user response:

If you what to return the max value and also ensure the all the inputs are number, you can use this method:

def max_of_three(a, b, c):
  if not (isinstance(a, (int, float)) and isinstance(b, (int, float)) and isinstance(c, (int, float))):
    return "Error: All inputs must be numbers."

  # Find and return the maximum of the three numbers
  if a >= b and a >= c:
    return a
  elif b >= a and b >= c:
    return b
  else:
    return c

print(max_of_three(3, 2, 1))  # Output: 3
print(max_of_three(3.5, 2.5, 1.5))  # Output: 3.5
print(max_of_three('3', 2, 1))  # Output: "Error: All inputs must be numbers."
  • Related