Why do we need to redefine something we’ve already defined?
We’ve defined low_limit and high_limit with equations and then when we tell the program get_boundaries(100, 20) this should tell what each key word in the equation means. Perhaps I take the ease with which computer do things normal for granted but having to introduce low and high seems to be an unnecessary step logically speaking.
I formatted your code, so we can see how you had originally indented it. Please review this post: How do I format code in my posts?
Regarding your code, these lines will never be executed:
Consider what return does. There is also no need for those lines to be executed. Values assigned to variable inside of a function have local scope (are only accessible inside the function). The values that are returned by the function are ‘unpacked’ and assigned to low and high in this line:
You are correct the variables inside a function are local to that function unless shenanigans are engaged, but that is outside the scope of this question.
If you’re curious there’s a good discussion of it over on stack overflow:
It has several commented code examples to help get the finer points across.
I found it much more intuitive to remain consistent with the variable naming scheme. I also added a print() line to check my work which seemed to vindicate my approach. Let me know if this doesn’t make sense to anyone else as I am pretty new to this stuff.
def get_boundaries(target, margin):
low_limit = target - margin
high_limit = margin + target
return low_limit, high_limit
# Two vairables areassigned to the same function call thereby returning two different values/results.
low, high = get_boundaries(100, 20)
# A print statement of the above removes the confusion
print(low, high)
Thanks, this helped me, I was clueless as to how I got my answer when the variable names do not match up, but it’s not about the variable names. You are calling the return values in order and the names do not have to match up, which confused me at first but seemed like the only explainable way for my programs results.
@mtf’s response about checking indentation and a moving a particular line outside the function block would be correct. In your code you’re using print as a function, which will print to the console, but it will return None to the names low and high.
Maybe I need more coffee, and I’m sure the answer is simple, but, I still have this question. Why save the values globally(?) when you can plug in any two numbers in the print() function?