`1linktotal = 0`

2linkfor n in four_million_sequence:

3link if n % 2 == 0:

4link total += n

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

- 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

`1linkdef generate_fibonacci_sequence(term_limit, first_term, second_term):`

2link sequence = [first_term, second_term]

3link while True:

4link next_number = sequence[-1] + sequence[-2]

5link if next_number < term_limit:

6link sequence.append(next_number)

7link else:

8link break

9link

10link return sequence

11link

12linkfour_million_sequence = generate_fibonacci_sequence(4000000, 1, 2)

13linkprint(sum([n for n in four_million_sequence if n % 2 == 0])) # // @see [List Comprehension](https://www.programiz.com/python-programming/list-comprehension)

- Let us first start by creating a function that generates a Fibonacci sequence. This accepts three
parameters:
`term_limit`

: the maximum number in the sequence`first_term`

: the first number in the sequence`second_term`

: the second number in the sequence

- The first and second terms are put into a list
`sequence`

- We go in this loop until
`next_number`

reaches the`term_limit`

.- The next number in the sequence is calculated by adding the last two numbers in the sequence, which is
`sequence[-1]`

and`sequence[-2]`

respectively. - Check if
`next_number`

is less than the`term_limit`

.

- The next number in the sequence is calculated by adding the last two numbers in the sequence, which is
- Running this function will show: 1linkprint(generate_fibonacci_sequence(10, 0, 1))2link[0, 1, 1, 2, 3, 5, 8]
- Another example:1linkprint(generate_fibonacci_sequence(90, 1, 2))2link[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
- Generate a Fibonacci sequence whose values do not exceed four million and that it starts with 1 and 2.
- We get the sum of all even numbers in the sequence by using list comprehension.This is shorthand for:chevron_right1linktotal = 02linkfor n in four_million_sequence:3link if n % 2 == 0:4link total += n

Show Answerchevron_right

4613732