0
0
Pythonprogramming~10 mins

Comparison magic methods in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define the method that checks if two objects are equal.

Python
class Box:
    def __eq__(self, other):
        return self.size [1] other.size
Drag options to blanks, or click blank then click option'
A!=
B=
C==
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single '=' which is assignment, not comparison.
Using '!=' which checks for inequality.
2fill in blank
medium

Complete the code to define the method that checks if one object is less than another.

Python
class Box:
    def __lt__(self, other):
        return self.weight [1] other.weight
Drag options to blanks, or click blank then click option'
A<
B>
C==
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' which means greater than.
Using '==' which means equal.
3fill in blank
hard

Fix the error in the method that checks if one object is greater than or equal to another.

Python
class Box:
    def __ge__(self, other):
        return self.height [1] other.height
Drag options to blanks, or click blank then click option'
A<=
B>=
C=>
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=>' which is not a valid Python operator.
Using '<=' which means less than or equal.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if the length is greater than 3.

Python
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if len(word) [2] 3}
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as the value instead of its length.
Using '<' instead of '>' in the condition.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase keys to values only if the value is positive.

Python
data = {'a': 1, 'b': -2, 'c': 3}
result = { [1]: [2] for k, v in data.items() if v [3] 0 }
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using original keys without uppercase.
Using '<' instead of '>' in the condition.
Swapping keys and values.