0

Implement the function test_number that takes as input a number and a string:

(one of 'even', 'odd', 'positive', or 'negative')

The function returns True if the number has the property indicated by the string, and False if it doesn't.

It works for the even/odd part, so I guess it's gives faulty results for positive/negative because I had put "else: return 'False'" earlier in the function.

Deer530
  • 73
  • 1
  • 1
  • 10
  • 1
    *First of all, what is "assert not"?* I bet this is answered in the preceding chapter of your textbook... – David Zemens Oct 16 '15 at 02:01
  • 1
    Return boolean `True` or `False` (no quotes) so that you can can rid of `== 'True'` in the `assert` statements. Also, you need to use `assert not` so you can test that your function fails correctly with e.g. `test_number(100, 'odd')`. – ekhumoro Oct 16 '15 at 02:16
  • @ekhumoro Thanks! This was exactly what I was wondering about (the assert not statements) – Deer530 Oct 16 '15 at 02:28

2 Answers2

2

First of all, what is "assert not"?

It's an assert statement with an expression that starts with the not logical negation operator.

And second of all, why is my code producing false results?

The first else reached returns False. Remove all else clauses and return False at the end, since that will be the default if nothing else is true.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • So I tried putting the else clause at the end (which worked), but when I put assert not statements, an error pops up. If I insert assert statements alone, the code works though. How can I make my code work with assert not statements? – Deer530 Oct 16 '15 at 02:24
  • Don't put an `else`. Just return. – Ignacio Vazquez-Abrams Oct 16 '15 at 02:24
0

You can put your property strings in a dictionary:

def test_number(n, s):
    conditions = {'even': (n % 2 == 0),
                  'odd': (n%2 == 1),
                  'positive': (n >=0),
                  'negative': (n<0)}

    return conditions.get(s, None)

assert test_number(14, 'even')
assert not test_number(100, 'odd')
assert test_number(33, 'positive')
assert not test_number(100, 'negative')
David Zemens
  • 53,033
  • 11
  • 81
  • 130