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! While you're at it, check out some resources Treehouse students have shared here.
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 trialStuart Main
586 Pointssquared.py
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)
square(3)
Any help is sincerely appreciated!!!!
def square(number):
result = number * number
return result
square(3)
print(result)
2 Answers
behar
10,799 PointsHey 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:
square(3)
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:
print(square(3))
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!
Stuart Main
586 PointsThanks again behar!
Stuart Main
586 PointsStuart Main
586 PointsThanks 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!!!
behar
10,799 Pointsbehar
10,799 PointsHey again Stuart! Yup you got it, keep on going!