Python tips for functions that return results

2022-11-22

Python's function returns results
Hello everyone, today we're going to talk about functions that return results. But the function we're using is a little bit more complicated.

We define def fibo (n), fibo is a name I gave myself, n represents how many items I want to return, and then the colon is the beginning and end of the function, and then the following should be indented.

Start by writing a equals 0, b equals 1, i=0, and result equals an empty list, all of which are variables that we know in advance.
Then while i is less than n, that is, if I want 5, I perform the following operation if this i is less than 5.

What is i? i starts with 0, that is, it starts at position 0, a value.

Then result.append (a). a is 0, and its first position is 0.

The next one is particularly important, a,b=b, a+b, that is, assigning values simultaneously. a is assigned to b and b is assigned to a+b.

Remember, a is 0 at this point, but b is 1, so when this assignment is made, a becomes 1, and then b is assigned to a+b.

Note that a here is still 0 and 1 is 1, because negative values are generated at the same time, so you can't take the a that has been assigned here and use it here.

This is followed by b is 1, a is 0, b is 1, then a and b are assigned to 1 and 0+1 is also 1, then i=i+1, to prepare for the next loop.

After the next second, i=i+1, i is still less than 5, continue to result.append just a it has been assigned to 1, 1 in and then continue to seek a, b are b and a + b assignment, that is, so a cycle, and continue to go until i is not less than the n you give, you get a result.
This result is returned, return is the way to return the result, we run it, and then change fibo to 10, we get 0, 1, 1 such a 10-bit Fibonacci sequence.

Why is it printed out automatically here?

First of all, return is the value returned, and the last line is printed by default in jupyter notebook, so there is a print operation here to show the result.

The most important thing to understand here is that this a, b it must be the original value to use when doing the assignment at the same time.

If you separate it into a=b and then b=a+b, then it has a sequential relationship, but here it is running at the same time, so you need to understand it well.

Python's Iteration Operations
Next, let's talk about traversal operations.

I've got an n, and if I iterate through it three times, I'll do for i in range (n), and then print (i). We'll get 0, 1, and 2. Why?

Because range (n) it actually means range (0) to your n, here is 3, is 0 to 3 such a range, this is our most common way of traversal.
When you don't know what the range is, you can use range (n) to print it out and see what it returns.

Thanks for watching

Join Us

Company/Organization Name:

Company/Organization Site:

Candidate Name:

Candidate Job:

Tel:

Email:

Admission Remarks: (cause and appeal of admission)

Submit application