0

I don't know why it still printing Arizona, and not raising a ValueError.The function also needs to be able to take Arizona in any case mix for example "ArIzOna" in the argument.

def raising_arizona(string):
    try:
        print(string)
        return True

    except:
        if string.upper() == 'Arizona' or string.lower() == 'arizona':
            raise ValueError
        return False

raising_arizona('Arizona')

I tried using an if statement in order for Arizona to be case-mixed by saying the string will be taken whether its lower or upper case.

  • 1
    Nothing in the `try` section can possibly fail. So you will never enter the `except` section. This function will always return True. – John Gordon Nov 18 '22 at 00:47
  • Your if statement is in the except section, which can’t be reached. – CharlieBONS Nov 18 '22 at 00:51
  • 1
    Why are you using `try/except` in the first place? Do you understand what they're for? – Barmar Nov 18 '22 at 01:01
  • `string.upper() == 'Arizona'` can never be true. The result of `string.upper()` will not have any lowercase letters in it, it would be `ARIZONA`. – Barmar Nov 18 '22 at 01:02
  • Does this answer your question? [Manually raising (throwing) an exception in Python](https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python) – Cireo Nov 18 '22 at 01:04
  • try looking for "case insensitive string equality" and "raise exception" and combine the two answers – Cireo Nov 18 '22 at 01:05

1 Answers1

0

The "try...except statement first runs the code in the try: section, and if it doesn't raise any exceptions (doesn't have an error) then it will skip over the except: section.

So, in you case, you are trying to print the passed argument and returning true. Neither of these lines throw an error, so the except section is skipped.

Also, you can do this with an if statement by first making all the letters of the passed argument lowercase and checking if that text is equal to "arizona":

def raising_arizona(string):
    if string.lower() == 'arizona':
        return string

raising_arizona('Arizona')
borderr
  • 165
  • 4