19 Review: Built in Functions


#1

Very stupid question, but why doesn't the following code display 6? I'm a little confused with the print and return in a function. Thanks in advance.

def distance_from_zero(num):

if type(num)==int or type(num)==float:

    return abs(num)

else:
    return "Nope"


distance_from_zero(-6)

#2

All you need to do is include print in your function call and it will,

def distance_from_zero(num):
    if type(num)==int or type(num)==float:
        return abs(num)
    else:
        return "Nope"

print distance_from_zero(-6)

#3

return really means the function returns something (hands you something back), we can see this:

def example():
    return 5
store = example()
print store

see how the function handed me something back? we can store this in a variable, and use it later, or as i did in this case, just print it. print just prints something, where return hands you something back. It is also important to realize, that return causes the function to end


#4

Hey guys, thanks for your help. Still having an issue, I'm using https://repl.it/languages/python3 to test my code, and when I enter:

def distance_from_zero(num):
    if type(num)==int or type(num)==float:
        return abs(num)
    else:
        return "Nope"
print distance_from_zero(-6)

It comes up with the error:

Traceback (most recent call last):
File "python", line 6
print distance_from_zero(-6)
^
TabError: inconsistent use of tabs and spaces in indentation

Please help, still not getting it to just print the result of: def distance_from_zero(-6).


#5

this means, you mix spaces and tabs, you can't do this in python, re-indent the code

I am confused, be careful, repl.it uses python3, which means print requires parentheses.


#6

Thanks Sterim94. This may seem like another dumb question, but where is the the best place to practice coding python?


#7

that depends, if you just quickly need to test something, repl.it is fine

personally, i would install python on your computer, this way, you can have many scripts stored on your computer and test as much as like, you could even use python to automate tasks


#8

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