Question

I am using Python 3.3.2 on a windows 7 32bit machine.

I am trying the following syntax:

def make_from(inputString):
    if inputString.endswith('y'):
        fixed = inputString[:-1] + 'ies'
    if inputString.endswith(('o', 'ch', 's', 'sh', 'x', 'z')):
        fixed = inputString[:] + 'es'
    else: 
        fixed = inputString + 's'
    return fixed

The first IF condition does not seem to be taking effect .. the others work for example if I type make_from('happy') it returns 'happys', but if it type make_from('brush') it returns 'brushes'.

I guess I am missing something.. any idea whats going on here.

Was it helpful?

Solution

When you enter happy the following two statements execute:

if inputString.endswith('y'):
    fixed = inputString[:-1] + 'ies'

and

else: 
    fixed = inputString + 's'

because the second if statement is False for happy. So fixed is first assigned happies but ends up as happys because the first assignment is replaced.

Use elif instead of if for the second test:

def make_from(inputString):
    if inputString.endswith('y'):
        fixed = inputString[:-1] + 'ies'
    elif inputString.endswith(('o', 'ch', 's', 'sh', 'x', 'z')):
        fixed = inputString[:] + 'es'
    else: 
        fixed = inputString + 's'
    return fixed

or use multiple return statements:

def make_from(inputString):
    if inputString.endswith('y'):
        return inputString[:-1] + 'ies'
    if inputString.endswith(('o', 'ch', 's', 'sh', 'x', 'z')):
        return inputString[:] + 'es'
    return inputString + 's'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top