Advanced and scientific Python

Logo

Materials to brush up your Python skills

View the Project on GitHub xoolive/pyclass

Basic types and arithmetic

Code snippets may either be:

  • typesetted with syntax coloring, or
  • prefixed with the >>> sign, which imitates the behaviour of the REPL1 interpreter.

You are encouraged to copy paste the snippets into your Python interpreter to become familiar with its behaviour.

Some elements of syntax

Python is a dynamically typed language: variables are untyped, but values are. In the following example, variable a can point to an integer, then to a string. However values 12 and "hello world" are resp. of types int and str.

>>> a = 12
>>> type(a)
int
>>> a = "hello world"
>>> type(a)
str

It is considered good practice to add type annotations to your code. We will see later how they can help writing a correct programme. Annotations are made of any valid Python syntax: they are placed after a column sign and are ignored at runtime. All the following annotations are valid.

a: int = 12
b: str = "hello world"
distance: float = 7.3
distance: "nautical_miles" = 7.3

At this point, consider type annotations as an additional way to comment or document your code with useful information.

The return type of functions can also be annotated after the -> symbol. In the following example, the fact function takes an integer as a parameter and returns an integer.

def fact(n: int) -> int:
    """Returns the factorial of n.

    >>> fact(6)
    720
    >>> [fact(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]

    n is negative, a ValueError exception is raised:

    >>> fact(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be a positive integer
    """
    res = 1
    if n < 0:
        raise ValueError("n must be a positive integer")
    while n > 0:
        res = n * res
        n = n - 1
    return res

You may note here that:

Exercice    Copy the code above in a new file fact.py (in Visual Studio Code).
Add the following import at the top of the file:
import doctest
and the following snipped at the bottom:
if __name__ == "__main__":
    print(doctest.testmod())
  • Execute the file and check the tests are correct.
  • Add examples (tests) so that the following examples return a meaningful value or exception.
    There is no unique answer here, it's really up to you.
    fact("12")
    fact(3.14)
    fact([1, 4, 7])
    

Basic types and arithmetic

Python offers a number of data structures with syntactic and algorithmic facilities. The art of programming consists in choosing (and adapting) the most appropriate data structure.

Exercices

All exercices are to be implemented in single files. Solutions are located in the solutions/basic/ folder.

  1. Write a function returning the Roman numeral representation of any integer between 1 and 3999.
    Test your function with the following numbers:

    • 476: "CDLXXVI"
    • 1515: "MDXV"
    • 1789: "MDCCLXXXIX"
  2. Write a function returning all prime integers below n (integer). Annotate your function and local variables with types and run tests with the doctest module.
    Hint: Sieve of Eratosthenes, then ask yourself what is the most appropriate structure to handle this.

  3. Find the lorem-ipsum.txt file in the data/ folder. Count the occurrences of all words in the text, and print the 10 most frequent words with their number of occurrences.
    You may start your code based on the following snippet:

    from pathlib import Path
    
    def main(filename: str) -> None:
        txt = Path(filename).read_text()
    
    if __name__ == "__main__":
        main("data/lorem_ipsum.txt")
    

↑ Home | » Next


Footnotes

  1. Read, Evaluate, Print, Loop (REPL) is the common behaviour of interactive shells, like the Python interpreter.