Type hints in Python
In this lesson, you will learn about Type Hints in Python and how to use them in your python program.
Type hints in Python
Unlike C programming, Python is a dynamically typed language. When you declare a variable in a python program, you don’t need to indicate the type of the variable (Ex. Str, int, float). It sounds more efficient, but not all the time. At times, dynamic typing can lead to errors, bugs that are very difficult to debug. That’s where the need for Type Hints arises. Type hints were first introduced in Python version 3.5. In type hints, you will be directly declaring the type of the variable being used in that part of the program.
Let’s understand type hints with the help of an example.
Sample program using Type Hints in Python
Input:
[gamipress_button label=”Try It” onclick=”window.open(‘https://coderseditor.com/?id=1405′,’_blank’)”]
def type_hint(name: str) -> str: return f'Welcome {name}' welcome = type_hint(576) print(welcome)
Output:
Welcome 576!
Take a look at the above example, here we have declared that the variable type is str, string. So that, even when you throw an integer in the print variable, the interpreter interprets it as a string and does not throw an error.