Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

For ValueError example there is created new function called find_item_possition_in_list:

...

The ValueError raised and test_find_item_position_in_list test passed.


 ValueError - advanced example

Firstly let's write another function called reshape_array.  The function arguments are a list (lst) and output array dimensions  (x and y). The result is an array containing the same data with a new shape. To transform list to array and reshape it there is the NumPy package needed. 

NumPy package installation:

Code Block
pip install numpy


If the NumPy package is installed we can import it and write the reshape_array function like in the snipped below:

Code Block
languagepy
import numpy as np


def reshape_array(lst, x, y):
    array = np.array(lst)
    return array.reshape((x, y))


It's impossible to reshape an array into any shape.  We can reshape an 4 elements 1D array into 2 elements in 2 rows 2D array but we cannot reshape it into a 2 elements 3 rows 2D array as that would require 2x3 = 6 elements. We can check that using Pytest.

Code Block
languagepy
def test_reshape_array():
    with pytest.raises(ValueError):
        reshape_array([1, 2, 3, 4], 2, 3)

    assert (reshape_array([1, 2, 3, 4], 2, 2) == np.array([[1, 2], [3, 4]])).all()

We used np. ndarray. all() to check if two arrays are equivalent. 


Image Added

The first test passed and raised a ValueError exception because there is no possibility to reshape the 4 elements list into 2x3 array. The second test also passed - a list of 4 elements can be reshaped into 2x2 array. 


Info
The official documentation with listed available python built-in exceptions: https://docs.python.org/3/library/exceptions.html

...