[ Web Proxy ]
URL:
Viewing: https://www.python-course.eu/python-tutorial/type-annotations.php [Back]  [Original]

7. Type Annotations | Python Tutorial | python-course.eu
python-course.eu
Search site:

Live Python classes by highly experienced instructors:

instructor-led training course [instructor-led training course]
Instructor-led training courses by Bernd Klein

  1. Intro to Python Tutorial
  2. History and Philosophy of Python
  3. The Interpreter, an Interactive Shell
  4. Execute a Script
  5. Structuring with Indentation
  6. Assignment Expressions
  7. Data Types and Variables
  8. Type Annotations
  9. Operators
  10. Sequential Data Types
  11. List Manipulation
  12. Shallow and Deep Copy
  13. Dictionaries
  14. Sets and Frozen Sets
  15. Sets Examples
  16. Keyboard Input
  17. Conditional Statements
  18. Structural Pattern Matching
  19. Adventure Game with Structural Pattern Matching
  20. While Loops
  21. For Loops
  22. Output with Print
  23. Formatted Output
  24. Working with Dictionaries and while Loops
  25. Functions
  26. Passing Arguments
  27. Parameters And Arguments
  28. Namespaces
  29. Global vs. Local Variables and Namespaces
  30. File Management
  31. Modular Programming and Modules
  32. Packages
  33. Errors and Exception Handling

This website contains a free and extensive online tutorial by Bernd Klein, using material from his classroom Python training courses.

If you are interested in an instructor-led classroom training course, have a look at these Python classes:

instructor-led training course [instructor-led training course]
Instructor-led training course by Bernd Klein at Bodenseo

Image kabliczech - Fotolia.com

This page was written by Melisa Atay.

Melisa is a Python enthusiast. If you have any comments, questions, concerns about the content of this page contact Melisa at [email protected]

PDF versions of this site [PDF versions of this site]

PDF logo [PDF logo] PDF version of this site

This website is free of annoying ads. We want to keep it like this. You can help with your donation:

[Go]

The need for donations

7. Type Annotations

By Melisa Atay. Last modified: 05 Jul 2022.

If you know another programming language such as C or C++, you are used to declaring what data type you are working with. For example, this is how you would declare an integer in C.

int a;

from this moment on, we know that "a" is of type integer. Then we would maybe assign an integer to a.

 a = 3 

However we don't do it like that in Python. Let's go through what we already know.

a = 3
print(type(a))

OUTPUT:

<class 'int'>

As a is assigned an integer, it belongs to the integer class itself, without us having to say

 a = int() 

beforehand. a's data type would change accordingly, when it is assigned values from other data types.

a = 'hello'
print(type(a))

OUTPUT:

<class 'str'>
a = 3.14
print(type(a))

OUTPUT:

<class 'float'>

If Python is capable of determining the types itself, why are even type annotations useful?

Type Annotations: Why

Live Python training

instructor-led training course [instructor-led training course]

Enjoying this page? We offer live Python training courses covering the content of this site.

See our Python training courses

See our Machine Learning with Python training courses

Type Annotations: How

Example 1

In this example you see the ord()function, which takes a string as input and converts it into an integer by using the ASCII values of the letters it contains.

def my_function(a:int,b:str)->int:
    return a + ord(b)
print(my_function(3,'a'))

OUTPUT:

100

my_function() works perfectly, since b has to be of type string and it is of type string. Let's try it otherwise:

print(my_function(3,5))

OUTPUT:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_19492/488431691.py in <module>
----> 1 print(my_function(3,5))

/tmp/ipykernel_19492/2046822703.py in my_function(a, b)
      1 def my_function(a:int,b:str)->int:
----> 2     return a + ord(b)

TypeError: ord() expected string of length 1, but int found

Here we receive a TypeError because we wrote an integer, and not a string for b. Since ord() needs a string to function, the code doesn't work.

print(my_function('a','a'))

OUTPUT:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_19492/1936946746.py in <module>
----> 1 print(my_function('a','a'))

/tmp/ipykernel_19492/2046822703.py in my_function(a, b)
      1 def my_function(a:int,b:str)->int:
----> 2     return a + ord(b)

TypeError: can only concatenate str (not "int") to str

Here we receive another TypeError because we wrote a string, and not an integer for a. While b is sucessfully converted into an integer by the ord() function, it is yet not possible to concatenate strings and integers.

print(my_function(4.2,'a'))

OUTPUT:

101.2

Interestingly our function runs now, yet our argument a is of type float and not integer as we declared at the very beginning.

Example 2:

In this example, we are going to see how the functions can be given variables that can work without raising any errors. However, that can be still be very problematic.

def add_together(a:int,b:int)->int:
    return a + b 
def return_the_last_digit(a:int)->int:
    return a % 10
our_sum = add_together(38,57)
print(return_the_last_digit(our_sum))

OUTPUT:

5
our_sum = add_together('add',' together')
print(return_the_last_digit(our_sum))

OUTPUT:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_19492/576833914.py in <module>
----> 1 print(return_the_last_digit(our_sum))

/tmp/ipykernel_19492/1809188113.py in return_the_last_digit(a)
      1 def return_the_last_digit(a:int)->int:
----> 2     return a % 10

TypeError: not all arguments converted during string formatting

How can we run a TypeError check before we actually run the program?

By installing mypy and running it before you run your code, you could avoid type errors. Mypy checks your annotations and gives a warning if a function is initialized with the wrong datatype.

Mypy [Mypy]

All in all, type annotations are very useful and it can save a lot of time for you and it can make your code readable for both yourself and the others.

Live Python training

instructor-led training course [instructor-led training course]

Enjoying this page? We offer live Python training courses covering the content of this site.

Upcoming online Courses

See our Python training courses

See our Machine Learning with Python training courses

top


Web Proxy Viewer  |  New URL  |  Original Page