Python Forum

Full Version: Proper use of if..elif..else statement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm a retired software engineer who has programmed in a large number of different languages, but I am new to Python. As my first effort at writing a Python script, I started working on a program to computer Fibonacci numbers. My initial code is shown below.
def Fibonacci():
    number = 3
    f1 = 1
    f2 = 1
    if number == 1:
        print (f1)
        elif number = 2:
            print (f2)
        else:
            n = 3
            while n <= number:
                f3 = f1 + f2
                f1 = f2
                f2 = f3
                print (f3)
                n = n + 1
However, I am getting a syntax error at the beginning of the "elif" line. Looking in the Python Language Reference showed by the syntax, but there were no examples I could find of actually using this structure. Could you please tell how to rework that elif statement so I do not get a syntax error? Thanks!

BTW, the code I pasted in was properly indented (I think), but I notice when viewed in the forum, it's all squished to the left.
Essentially, this is an identation error. If/elif/else statements in Python
have the following syntax:

if statement1:
    ... some code
elif statement2:
    .... some code
else:
    .... some code
So, you need to fix identations in your code, e.g.
def Fibonacci():
    number = 3
    f1 = 1
    f2 = 1
    if number == 1:
        print (f1)
    elif number == 2: # (NOTE: = is an assignment operator; == is used for comparison)
        print (f2)
    else:
        n = 3
        while n <= number:
            f3 = f1 + f2
            f1 = f2
            f2 = f3
            print (f3)
            n = n + 1
Thanks for the help. The "number = 2" was really a typo. I know it should have been "==".