Proper use of if..elif..else statement - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Proper use of if..elif..else statement (/thread-24821.html) |
Proper use of if..elif..else statement - nick1941 - Mar-05-2020 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 + 1However, 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. RE: Proper use of if..elif..else statement - scidam - Mar-06-2020 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 codeSo, 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 RE: Proper use of if..elif..else statement - nick1941 - Mar-06-2020 Thanks for the help. The "number = 2" was really a typo. I know it should have been "==". |