Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Functions and Looping Create a Function


Hi guys, really struggling here... I know this should be easy but the challenge wont pass me. It runs and prints the correct number in the Workspace: def square(number): result = number * number print(result)


Any help is sincerely appreciated!!!!

def square(number):
    result = number * number 
    return result



2 Answers

Hey Stuart! Because of the concept of scope, outside the 'square' function the variable 'result' actually does not exist, therefor you will get a compiler error.

Also there is something import you seem to have misunderstood, when you call a function like you did in when you said:


The result from this is not saved inside the variable 'result', and cannot be used later outside the function. Instead the result is imidiately returned from the function.

Therefor, simply say:


Also two ways that will make your code smaller is to, instead of saving the square of the number into a variable called result, why don't you just imidiately return the answer:

def square(number):
    return number * number

And finally there is an operator for squaring, instead of saying num * num, you can say num ** 2.

Hope this helps, and good luck!

Thanks mate, you nailed it! If I may paraphrase; 1). scope refers to variables defined inside/ outside of a function. Just because you have named a variable inside a function does not mean you can reference it outside of the function. 2). you can print the output of a function without defining it as a variable vis print(square(3)) #super helpful thanks mate I was tinkering with this for ages 3). tasty notation num ** 2 indeed

Have I understood?

Also, thanks heaps Behar!!!! your time is appreciated!!!

Hey again Stuart! Yup you got it, keep on going!

Thanks again behar!