-1

My goal is to write a code that checks if a given string is a palindrome (same word forwards and backwards) and so far I have this

def is_palindrome(s):
    string = s
    if (string==string[::-1]):
        print("The string IS a palindrome")
    else:
        print("The string is NOT a palindrome")
    return

When I run these two asserts however, it only types out "The string IS a palindrome" once for the first assert and not "The string is NOT a palindrome" for the assert with 'house'

assert is_palindrome('noon')
assert not is_palindrome('house')

So for some reason that I can't see it must be only executing the function once. Can someone help me by telling me where the problem is?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
DQuijote
  • 11
  • 1

2 Answers2

0

The problem is that the return value of your function is always None, so the assert is_palindrome(...) will fail and raise an AssertionError. Any statement following this (in this case your assert not is_palindrome('house')) will not be executed.

What you need to do is return an appropriate value. For example:

def is_palindrome(s):
    string = s
    if (string==string[::-1]):
        print("The string IS a palindrome")
        return True
    else:
        print("The string is NOT a palindrome")
        return False
alani
  • 12,573
  • 2
  • 13
  • 23
  • Can even get rid of `else` because of early return. – Mario Ishac Sep 11 '20 at 11:01
  • @MarioIshac Yes, you can get rid of the `else`. Whether to do so or not is a stylistic decision, and personally I think it is clearer with the `else` still there. – alani Sep 11 '20 at 11:02
  • Yes, now it worked! What is the logic behind this? I thought I already said that if it is a palindrome write this, if not write this and then return to do it for as many times as needed. What does return True/False do? – DQuijote Sep 11 '20 at 11:03
  • @DQuijote It will use the relevant boolean value (`True` or `False`) as the return value of the function, and return control back to the caller. The `assert` in the caller will test for this and if the value is false (which in fact includes various other values that are treated as false, e.g. `0`, but here we are actually using `False`) then you get the `AssertionError` that I mentioned. In your code you were just printing a human-readable message but not doing anything that would control the behaviour of the `assert`. – alani Sep 11 '20 at 11:06
-3

What are you asserting when you say assert is_palindrome('noon')

Your function returns None, if you assert that you won't get any error assert is_palindrome('noon')==None

def is_palindrome(s):
    string = s
    if (string==string[::-1]):
        print("The string IS a palindrome")
        return True
    else:
        print("The string is NOT a palindrome")
        return False

assert is_palindrome('noon')
assert not is_palindrome('house')
assert is_palindrome('house')
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22