I'm new to python and run into a problem. I tried to resolve the problem with functions, but without success. Maybe somebody can tell me what I did wrong.
This is the problem. I resolved it without functions and it works.
#!/usr/bin/python3
########################################################################################################################################################
### ###
### 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, ... ###
### ###
### Find the sum of all the even-valued terms in the sequence which do not exceed four million. ###
### ###
########################################################################################################################################################
n = int(input('Give n:'))
fib1, fib2 = 1, 1
fibo = fib1 + fib2
s=0
while fibo <= n:
if fibo % 2 == 0:
s += fibo
fib1 = fib2
fib2 = fibo
fibo = fib1 + fib2
print('Sum is:', s)
print('--- Done ---')
Now this is what I tried to do. A function for the Fibonacci sequence, but it doesn't work. It seems to do an infinite loop in the terminal. What did I do wrong?
#!/usr/bin/python3
n = int(input('Give n:'))
s = 0
fib1, fib2 = 1, 1
fibo = fib1 + fib2
def fibonacci(fib1, fib2):
fibo = fib1 + fib2
yield fibo
fib1 = fib2
fib2 = fibo
while fibo <= n:
if fibo % 2 == 0:
s += fibo
fibonacci(fib1, fib2)
print('Sum is:', s)
print('--- Done ---')
Sorry for any writing mistakes, my English isn't that good.


Sign In
Create Account

Back to top









