Python Functions Practice makes perfect


#1

My code:-
def cube(number):
return number**3

def by_three(number):
if type(number/3)==int:
return cube(number)
else:
return False

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

What do i do to fix this? I tried keeping “return False” under else, i tried indenting it. Nothing worked. Would appreciate it if someone could help


#2

Hi @xboxaryan,

There may be a problem with the indentation of your else block, but since you did not format your posted code, its indentation is not visible.

See Quick Tips for Writing Good Posts for advice.


#3
def cube(number):

return number**3

def by_three(number):

if type(number/3)==int:

return cube(number)

else:

return False

#4

Is what you have posted identical to the code that you submitted to the Python interpreter? If so, your code does not have any indentation.

Examine the structure of the shout function that is presented as an example in this exercise. Everything within the function body is indented. Within the if and else blocks, there is additional indentation. Model your code after that example.

Also review the % operator. Instead of this …

if type(number/3)==int:

… use that operator to test for divisibility by 3. Recall that in Python 2, the / operator will yield an int if both operands are ints. The test that you are using will not perform as intended.


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

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

This is my original code with indentation, but still the error is :-

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


#6

I indented the else statement :
def cube(number):
return number**3

def by_three(number):
if number%3 ==int:
return cube(number)
else:
return false

and the next problem was this : -
File “python”, line 8
return false
^
IndentationError: unindent does not match any outer indentation level


#7

@xboxaryan,

Whenever you post code, please format it.

Since your most recent post is not formatted, we cannot see its indentation, which is unfortunate because that is the source of one of the current problems.

In the previous post, you have this …

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

You need to indent the entire else block. The final return statement needs to be indented to a further degree than the else header, so that it is part of the else block. Remember to use only spaces for indentation in your code within the Codecademy environment. Some of your lines are indented with tabs.

In your most recent post, false begins with a lowercase letter. It needs to be uppercase.

Also revise this line …

	if number%3 ==int:

You need to check for a result of 0. This tests number for divisibility by 3

	if number % 3 == 0:

#8

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