Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/data_types/test_dictionaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def test_dictionary():

# To check whether a single key is in the dictionary, use the in keyword.
assert 'apple' in fruits_dictionary
assert fruits_dictionary['apple'] == 'green'
assert 'pineapple' not in fruits_dictionary

# Change the apple color to "red".
Expand Down Expand Up @@ -66,7 +67,7 @@ def test_dictionary():

# In addition, dict comprehensions can be used to create dictionaries from arbitrary key
# and value expressions:
dictionary_via_expression = {x: x**2 for x in (2, 4, 6)}
dictionary_via_expression = {x: x**2 for x in range(10) if x % 2 == 0}
assert dictionary_via_expression[2] == 4
assert dictionary_via_expression[4] == 16
assert dictionary_via_expression[6] == 36
Expand Down
24 changes: 19 additions & 5 deletions src/data_types/test_lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def test_list_type():
assert squares[0] == 1 # indexing returns the item
assert squares[-1] == 25
assert squares[-3:] == [9, 16, 25] # slicing returns a new list

assert squares[4:] == [25]
# All slice operations return a new list containing the requested elements.
# This means that the following slice returns a new (shallow) copy of
# the list:
Expand Down Expand Up @@ -59,7 +59,7 @@ def test_list_type():
assert letters == ['a', 'b', 'f', 'g']
# clear the list by replacing all the elements with an empty list
letters[:] = []
assert letters == []
assert not letters

# The built-in function len() also applies to lists
letters = ['a', 'b', 'c', 'd']
Expand Down Expand Up @@ -263,8 +263,8 @@ def test_list_comprehensions():

# Call a method on each element.
fresh_fruit = [' banana', ' loganberry ', 'passion fruit ']
clean_fresh_fruit = [weapon.strip() for weapon in fresh_fruit]
assert clean_fresh_fruit == ['banana', 'loganberry', 'passion fruit']
clean_fresh_fruit = [weapon.strip().replace("banana", "apple") for weapon in fresh_fruit]
assert clean_fresh_fruit == ['apple', 'loganberry', 'passion fruit']

# Create a list of 2-tuples like (number, square).
square_tuples = [(x, x ** 2) for x in range(6)]
Expand Down Expand Up @@ -299,6 +299,16 @@ def test_nested_list_comprehensions():
[4, 8, 12],
]

# Square and transpose of a matrix:

squared_transposed_matrix = [[row[i]*row[i] for row in matrix] for i in range(len(matrix[0]))]

assert squared_transposed_matrix == [
[1, 25, 81],
[4, 36, 100],
[9, 49, 121],
[16, 64, 144]
]
# As we saw in the previous section, the nested listcomp is evaluated in the context of the
# for that follows it, so this example is equivalent to:
transposed = []
Expand All @@ -311,7 +321,11 @@ def test_nested_list_comprehensions():
[3, 7, 11],
[4, 8, 12],
]

assert list(zip(*squared_transposed_matrix)) == [
(1, 4, 9, 16),
(25, 36, 49, 64),
(81, 100, 121, 144),
]
# which, in turn, is the same as:
transposed = []
for i in range(4):
Expand Down
1 change: 1 addition & 0 deletions src/data_types/test_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def test_booleans():

assert isinstance(true_boolean, bool)
assert isinstance(false_boolean, bool)
assert(isinstance(true_boolean,int))

# Let's try to cast boolean to string.
assert str(true_boolean) == "True"
Expand Down
6 changes: 4 additions & 2 deletions src/data_types/test_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ def test_sets():

# It is also possible to use the set() constructor to make a set.
# Note the double round-brackets
fruits_set_via_constructor = set(("apple", "banana", "cherry"))

fruits_set_via_constructor = set(("apple", "banana", "cherry","strawberry","apple"))
assert fruits_set_via_constructor == {"apple", "banana", "cherry", "strawberry"}
assert isinstance(fruits_set_via_constructor, set)


Expand Down Expand Up @@ -65,6 +65,8 @@ def test_set_methods():
# Letters in first or second word but not both.
assert first_char_set ^ second_char_set == {'r', 'd', 'b', 'm', 'z', 'l'}

# Letters in first or second but not in both
assert first_char_set.symmetric_difference(second_char_set) == {'r', 'd', 'b', 'm', 'z', 'l'}
# Similarly to list comprehensions, set comprehensions are also supported:
word = {char for char in 'abracadabra' if char not in 'abc'}
assert word == {'r', 'd'}
15 changes: 10 additions & 5 deletions src/data_types/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def test_string_type():

# However, out of range slice indexes are handled gracefully when used
# for slicing:
assert word[4:42] == 'on'
assert word[:42] == 'Python'
assert word[42:] == ''

# Python strings cannot be changed — they are immutable. Therefore,
Expand Down Expand Up @@ -135,8 +135,9 @@ def test_string_operators():
text = (
'Put several strings within parentheses '
'to have them joined together.'
' Testing to add the third string.'
)
assert text == 'Put several strings within parentheses to have them joined together.'
assert text == 'Put several strings within parentheses to have them joined together. Testing to add the third string.'

# If you want to concatenate variables or a variable and a literal, use +:
prefix = 'Py'
Expand All @@ -162,7 +163,7 @@ def test_string_methods():
assert hello_world_string.upper() == 'HELLO, WORLD!'

# The replace() method replaces a string with another string.
assert hello_world_string.replace('H', 'J') == 'Jello, World!'
assert hello_world_string.replace('H', 'J').replace("W", "w") == 'Jello, world!'

# The split() method splits the string into substrings if it finds instances of the separator.
assert hello_world_string.split(',') == ['Hello', ' World!']
Expand All @@ -186,7 +187,11 @@ def test_string_methods():
my_tuple = ('John', 'Peter', 'Vicky')
assert ', '.join(my_tuple) == 'John, Peter, Vicky'

# Returns True if all characters in the string are upper case.

arr = ["1", "2", "3", "4", "5"]
assert ','.join(arr) == '1,2,3,4,5'

# Returns True if all characters in the string are upper case.
assert 'ABC'.isupper()
assert not 'AbC'.isupper()

Expand Down Expand Up @@ -221,7 +226,7 @@ def test_string_formatting():
no_votes = 43_132_495 # equivalent of 43132495
percentage = yes_votes / (yes_votes + no_votes)

assert '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage) == ' 42572654 YES votes 49.67%'
assert f'{yes_votes:8} YES votes {percentage:3.3%}' == '42572654 YES votes 49.673%'

# When you don’t need fancy output but just want a quick display of some variables for debugging
# purposes, you can convert any value to a string with the repr() or str() functions. The str()
Expand Down
2 changes: 1 addition & 1 deletion src/data_types/test_tuples.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def test_tuples():
assert first_tuple_number == 12345
assert second_tuple_number == 54321
assert third_tuple_string == 'hello!'

assert (first_tuple_number, second_tuple_number, third_tuple_string) == (12345, 54321, 'hello!')
# This is called, appropriately enough, sequence unpacking and works for any sequence on the
# right-hand side. Sequence unpacking requires that there are as many variables on the left
# side of the equals sign as there are elements in the sequence. Note that multiple assignment
Expand Down
4 changes: 2 additions & 2 deletions src/data_types/test_type_casting.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def test_type_casting_to_integer():

assert int(1) == 1
assert int(2.8) == 2
assert int('3') == 3
assert int('399') == 399


def test_type_casting_to_float():
Expand All @@ -34,7 +34,7 @@ def test_type_casting_to_float():
assert float(1) == 1.0
assert float(2.8) == 2.8
assert float("3") == 3.0
assert float("4.2") == 4.2
assert float("4.20000") == 4.2


def test_type_casting_to_string():
Expand Down
13 changes: 11 additions & 2 deletions src/exceptions/test_handle_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,16 @@ def test_handle_exceptions():
# We should get here because of division by zero.
exception_has_been_handled = True

assert exception_has_been_handled
exception_message = "No exception"
try:
result = 10 * (1 / 0) # division by zero
# We should not get here at all.
assert result
except Exception:
# We should get here because of division by zero.
exception_message = "Zero Division Exception"

assert exception_message == "Zero Division Exception"

# Let's simulate undefined variable access exception.
exception_has_been_handled = False
Expand Down Expand Up @@ -95,7 +104,7 @@ def test_handle_exceptions():
try:
result = 10
# We should not get here at all.
assert result
assert result == 10
except NameError:
# We should get here because of division by zero.
exception_has_been_handled = True
Expand Down
3 changes: 3 additions & 0 deletions src/exceptions/test_raise_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ def test_user_defined_exception():
# that may occur in functions they define.
class MyCustomError(Exception):
"""Example of MyCustomError exception."""
type = "Exception"
def __init__(self, message):
super().__init__(message)
self.message = message


custom_exception_is_caught = False

Expand All @@ -47,3 +49,4 @@ def __init__(self, message):
custom_exception_is_caught = True

assert custom_exception_is_caught
assert MyCustomError.type == "Exception"