def fib(n): a,b=1,1 for i in range(n-1): a,b=b,a+b return a print(fib(7))
时间: 2024-05-05 09:15:21 浏览: 97
The function `fib(n)` calculates and returns the nth number in the Fibonacci sequence using a loop.
Here's how it works:
1. The function takes a single argument `n`, which represents the position of the number in the sequence that we want to calculate.
2. We initialize two variables `a` and `b` to 1. These variables will be used to keep track of the previous two numbers in the sequence.
3. We loop `n-1` times (since we've already initialized the first two numbers), and in each iteration we update `a` and `b` to be the next two numbers in the sequence. We do this by setting `a` to `b`, and `b` to the sum of the old values of `a` and `b`.
4. Once the loop is done, we have calculated the nth number in the sequence, which is stored in `a`. We return this value.
5. Finally, we call the function with an argument of 7, and print the result.
The output of this code will be:
```
13
```
阅读全文