I was taking my course at codeacademy until something went wrong and couldn't proceed, a little help please :( here is my code
def by_three(num):
if num%3 == 0:
def cube(num):
else:
print "False"
def cube(num):
return num**3
by_three(9)
I get...
File "<stdin>", line 4
else:
^
IndentationError: expected an indented block
Unknown error.
I will really appreciate your help people!!
You probably wanted to call (use) the function cube() instead of defining it (in your by_three() function definition), so your corrected code will be:
def by_three(num):
if num%3 == 0:
print cube(num) # Instead of your original "def cube(num):"
else:
print "False"
def cube(num):
return num**3
by_three(9)
On line 3 def cube(num): you have an extra def and :. Remove those
When defining a function you need def and colon, where as for calling it you don't need one. The correct code
def by_three(num):
if num%3 == 0:
cube(num)
else:
print "False"
def cube(num):
return num**3
by_three(9)
Related
I've written simple code to handle just one case and correct the indentation (again simple and it relies on the user taking caution while using it) of a string containing a Python function declared using the def keyword and execute it.
def fix_index(string):
i=0;
t=string.find("def")+3;
string=string.replace(string[string.find("def"):t], "#")
while string.find(" ") != -1:
string = string.replace(" ", "")
i += 1
l=list(string);l[string.find(":")-i+2]+="$$$$"
return "".join(l).replace("$$$$", " ").replace("#", "def ").lstrip();
def switch(exp):
def exec(obj):
items = obj.items();
for k, v in items:
if(k==exp):
print(fix_index(v))
return eval(fix_index(v))();
return {"case":exec};
bread = "bread"
switch(bread)["case"]({
"cheese":
"""
def a():
print("cheese");
""",
"bread":
"""
def b():
print("bread");
"""
})
the output for the formatted function string:
C:\Users\User>python -u "c:\Users\User\folder\switch.py"
def b():
print("bread");
the error I'm getting:
Traceback (most recent call last):
File "c:\Users\User\folder\switch.py", line 27, in <module>
switch(bread)["case"]({
File "c:\Users\User\folder\switch.py", line 21, in exec
return eval(fix_index(v))();
File "<string>", line 1
def b():
^
SyntaxError: invalid syntax
I've also just realized I didn't name the function what I indented intended to (should've posted this when awake to avoid accidental pun).
Anyways what I fail to understand is what part in my produced string exactly contains "invalid syntax".
I'll appreciate any help.
if what you are looking for is to reproduce a switch statement, you can do it with the following function:
def switch(v): yield lambda *c: v in c
It simulates a switch statement using a single pass for loop with if/elif/else conditions that don't repeat the switching value:
for example:
for case in switch(x):
if case(3):
# ... do something
elif case(4,5,6):
# ... do something else
else:
# ... do some other thing
It can also be used in a more C style:
for case in switch(x):
if case(3):
# ... do something
break
if case(4,5,6):
# ... do something else
break
else:
# ... do some other thing
For your example, it could look like this:
meal = "bread"
for case in switch(meal):
if case("cheese"):
print("Cheese!")
elif case("bread"):
print("Bread!")
or this:
meal = "bread"
for case in switch(meal):
if case("cheese"):
print("Cheese!")
break
if case("bread"):
print("Bread!")
break
Instructions:
First, def a function called distance_from_zero, with one argument (choose any >argument name you like).
If the type of the argument is either int or float, the function should return >the absolute value of the function input.
Otherwise, the function should return "Nope"
I've done the first task and I thought that i completed the task, however
"Your function seems to fail on input True when it returned 'None' instead of 'Nope'"
Here is my code:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
return abs(argument)
print(argument)
else:
print("Nope")
From what ive seen in other modules codecademy tests this with my arguement being "1", such that the if statement goes through, will return the absolute value of (argument) and then i would pass the module. (i added print(argument) for testing purposes, the console outputs nothing.)
Am i mis understanding how returning works? Why is this not working?
I appreciate all responses! :)
EDIT: It prints "None", not "Nope" in the console. Forgot to mention this.
In Python, if return isn't explicit, it becomes None. Try this:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
print(abs(argument))
else:
print("Nope")
> f = distance_from_zero(-4234)
4234
> f
None
As you can see the value of f is None, this is because print is outputting to the console and not actively returning content. Instead, try using the return statement:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
return abs(argument)
else:
return "Nope"
> distance_from_zero(123)
123
# here, because you're not assigning the value returned to a variable, it's just output.
> f = distance_from_zero(-4234)
> f
4234
> f = distance_from_zero('cat')
> f
'Nope'
It's also important to know that the reason this:
return abs(argument)
print(argument)
printed to the console is not because of the print call. Anything after return in a block is not executed. The reason you see the output printed to the screen is because in the interpreter Python outputs all function return values not collected into variables.
def distance_from_zero(num):
if type(num) == int or type(num) == float:
return abs(num)
else:
return "Nope"
I keep getting an invalid syntax error at the kapfun(i) line in the createlist function. Can anyone tell me why?
def createlist(i):
n=i
global n
a=n[0:1]
b=n[1:2]
c=n[2:3]
d=n[3:4]
n=[int(a),int(b),int(c),int(d)
kapfun(i)
return i
def kapfun(i):
print(i)
kaprekar=down(i)-up(i)
return kaprekar
def integer(numList):
integer= ''.join(map(str, numList))
return int(integer)
def up(n):
n.sort()
up=n
up=integer(up)
return up
def down(n):
print(n)
n.reverse()
down=n
down=integer(down)
return down
def kaprekarfunction(i):
createlist(i)
print (i)
kapfun(i)
print (i)
return i
x="1234"
createlist(x)
print(x)
You are missing the bracket at the end of your list on the previous line. It should be:
n=[int(a),int(b),int(c),int(d)]
This is my program and I am getting the following mentioned error:
def main():
print "hello"
if __name__=='__main__':
main()
Error
File "hello.py", line 8
main()
^
IndentationError: expected an indented block
Your indentation is off. Try this :
def main():
print "hello"
if __name__=='__main__':
main()
All function blocks, as well as if-else, looping blocks have to be indented by a tab or 4 spaces (depending on environment).
if condition :
statements //Look at the indentation here
...
Out-of-block //And here
Refer to this for some explanation.
Normal Code
Indent block
Indent block
Indent block 2
Indent block 2
You should do:
def main():
print "hello"
if __name__=='__main__':
main()
It can be either spaces or tabs.
Also, the indentation does NOT need to be same across the file, but only for each block.
For example, you can have a working file like this, but NOT recommended.
print "hello"
if True:
[TAB]print "a"
[TAB]i = 0
[TAB]if i == 0:
[TAB][SPACE][SPACE]print "b"
[TAB][SPACE][SPACE]j = i + 1
[TAB][SPACE][SPACE]if j == 1:
[TAB][SPACE][SPACE][TAB][TAB]print "c
Your code should look like:
def main():
print "hello"
if __name__=='__main__':
main()
You probably want something like:
def main():
print "hello"
if __name__=='__main__':
main()
Pay attention to the indentations. Leading whitespace at the beginning of a line determines the indentation level of the line, which then is used to determine the grouping of statements in Python.
Just sharing this stupidity. I had a very similar error IndentationError: expected an indented block def main() since I had commented out the whole body of a previous "some_function".
def some_function():
# some_code
# return
def main():
print "hello"
if __name__=='__main__':
main()
This is more of a syntax error issue, I am trying to do this tutorial on Python Decorators
http://www.learnpython.org/page/Decorators
My Attempted Code
def Type_Check(correct_type):
def new_function(old_function):
def another_newfunction(arg):
if(isintance(arg, correct_type)):
return old_function(arg)
else:
print "Bad Type"
#put code here
#Type_Check(int)
def Times2(num):
return num*2
print Times2(2)
Times2('Not A Number')
#Type_Check(str)
def First_Letter(word):
return word[0]
print First_Letter('Hello World')
First_Letter(['Not', 'A', 'String'])
I am wondering whats wrong, please help
It looks like you forgot to return the newly defined function at the end of the decorator :
def Type_Check(correct_type):
def new_function(old_function):
def another_newfunction(arg):
if(isinstance(arg, correct_type)):
return old_function(arg)
else:
print "Bad Type"
return another_newfunction
return new_function
EDIT : there was also some types, fixed by andrean