Ask coding questions

← Back to all posts
why is this not working?
dbates (10)

So i'm trying to make the fibonacci sequence (google it) but my code is not working :( (it is driving me nuts so I need help)

Answered by ErrorNoInternet (18) [earned 5 cycles]
View Answer
Comments
hotnewtop
ErrorNoInternet (18)

Copy and paste this code exactly:

num1 = 1
num2 = 1
awncer = 2
def fibonacci():
    global num1, num2
    awncer = num1+num2
    print(awncer)
    num1 = awncer
    num2 = awncer
while (awncer != 1):
    fibonacci()
ZhongRietveld (30)

This must be on your first line in the functie:

global num1, num2

dbates (10)

thank you all so much! I am still having some issues though even after I added the global line.

RYANTADIPARTHI (6019)

@dbates ok, you're problem is you aren't putting indentation. So try commenting your entire code, and while it's commented, retype that code again. IT should work.

RYANTADIPARTHI (6019)

global gets those variables inside of your function. So use global <variable name>. In your case.

global num1, num2

that should work

OldWizard209 (1498)

The scope of your variables is local meaning it will only work on the specific function block. To make the scope global, so that you can use the variable in all function, use the global keyword, altering your code like:

num1 = 1
num2 = 1
awncer = 2
def fibonacci():
    global num1
    global num2
	awncer = num1 + num2
	print(awncer)
	num1 = awncer
	num2 = awncer
    
while (awncer != 1):
	fibonacci()
EmmaGao8 (33)

add a line in the beginning of your func:
global num1
global num2
global awncer

EmmaGao8 (33)

num1 is out of scope

robowolf (548)

https://www.python.org/ There should be a Fibonacci example.