5/20 Functions


#1

def cube(number):
return number**3

def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False


#2

You probably do not know this but you can do this,

Ternary Functions

def cube(number):
    return number**3

def by_three(number):
    return cube(number) if number % 3 ==0 else False

#3

Thanks pal this works fine but why you have not used colon at the end of if and else, its also stated in HINT to use that format. I actually didn't understand this, from the last exercises that i have done i have been using the given format, please let me know what was the logic behind this.


#4

Well ternary functions are different from a normal function, as you can see.

I don't think codeacendamy ever gets into them or even mentions them but they are useful.

With ternary functions you can assign a variable something only if it passes a condition and if it doesn't you can specify a different value to fill it with.

It's the same as doing

def by_three(number):
    if number % 3 == 0:
        return cube(number)
    else:
        return False

Just a lot shorter. Other programming languages also have ternary functions but python differs in the way they are used.