Functions Practice makes perfect


#1

Hello there,

this is my function:

def cube(number):
return number * number * number

def by_three(number):
if number % 3 == 0:
return cube(number)
print “n is divisible by 3”

else:
return False
print “n is not”

and this is the error I keep on getting:

File “python”, line 9
else:
^
SyntaxError: invalid syntax

What am I doing wrong here? why is my else statement not recognized?


#2

Since the exercise is based upon exponentiation it will do well to practice using the exponent operator…

return number ** 3

Statement after return is unreachable.

Likewise unreachable.

Be sure to check your indentation. The else: should be in line with if.


#3

Thanks, but my else is in line with my if and I now put the statements before the returns and I keep getting the same error message


#4
def cube(number):
  return number ** 3

def by_three(number):
  if number % 3 == 0:
     print "n is divisible by 3"
  return cube(number)
  else:
     print "n is not"
    return False

#5

Now I got it. wrong indentation indeed


#6

Form a habit of using four space characters for each level of indentation.

def ___():
    if ____:
        return ____
    else:
        return ____

Python is very particular about indentation since it denotes block scope and how the code is to be interpreted. Become a stickler for consistent and proper indentation.

I don’t believe the print statements are asked for, but if they are accepted, no harm, no foul. Best to never embellish code in lessons. Write only what is expected for best results.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.