ELI5. What does “return” do in programming? I read about it a lot and still dont understand the purpose.

334 views

ELI5. What does “return” do in programming? I read about it a lot and still dont understand the purpose.

In: 0

10 Answers

Anonymous 0 Comments

Computers do lots of calculations. The vast majority of the time, you don’t want to actually know the answer to a calculation. You only want to know a certain thing when a certain other thing happens. You use “return” to output the answer.

Let’s say you want to look for Pythagorean triples, three numbers a, b and c such that a²+b²=c², where a, b and c are all positive whole numbers. You get the computer to run through different options for a and b. It will square them and add them together. Then, it takes the square root of that and checks if it’s a whole number. If it is, then you’ve found one and you want to know about it. But the rest of the time, you don’t care!

You’d maybe set up the code to try 1²+2²=1+4=5. It tries √5, but it’s not a whole number.

Okay, now it tries 1²+3²=1+9=10. But √10 doesn’t work either.

Then 2²+3²=4+9=13, but √13 ×

1²+4² fails.

2²+4⁴ fails.

But 3²+4²=9+16=25 and √25=5. So the computer has found a solution and *returns* 3,4,5.

You are viewing 1 out of 10 answers, click here to view all answers.