Python, like JavaScript and Ruby, and many other languages, is dynamically typed. This means that a variable like name could change from an int to a string to a list, to whatever else it needs to be. However, we can hint at what types we should be using, but they’re not required and they’re not binding.
def add(num1: int, num2: int) -> int:
return num1 + num2
def sub(num1: int, num2: int) -> int:
return num1 - num2
def multiply(num1: int, num2: int) -> int:
return num1 * num2
def divide(num1: int, num2: int) -> float:
return num1 / num2
print(sub(9, 3))
print(add(5, 8.2))
print(multiply('Hello', 5))
num1: int
Type of num1 should be int
-> float
add() function returns float
Running those three print
commands will output valid results and will produce no errors.
However, an IDE that supports type hinting will tell you that you’re using the wrong argument types for the two last print commands.
To solve the second print command hint error, we can use the other number types from imported libraries that include floats and ints in one type, like complex and Real.
from numbers import Real
def add(num1: Real, num2: Real) ->:
return num1 + num2
def sub(num1: int, num2: int) -> int:
return num1 - num2
def multiply(num1: int, num2: int) -> int:
return num1 * num2
def divide(num1: int, num2: int) -> float:
return num1 / num2
print(sub(9, 3))
print(add(5, 8.2))
print(multiply('Hello', 5))