n1 = 0
n2 = 1
fiblist = []
while True:
newNum = n1 + n2
fiblist.append(newNum)
n1 = n2
n2 = newNum
if newNum >= 10000:
print(flist)
break
beginner programmer: is there an easier way to write this or some other more effective way
Your code can be simplified to the following.
fiblist = [0, 1] # initialize with first two numbers
while fiblist[-1] < 10000: # while last number <= threshold
fiblist.append(fiblist[-1] + fiblist[-2]) # next is sum of last 2 numbers
print(fiblist)
Explanation (provided since you asked for things to learn to be a better coder)
Simplification of your code to above based upon principles from two references
Using reference 1
PEP 8 Guide: "Function names should be lowercase, with words separated by underscores as necessary to improve readability". This is Python-specific. Other languages (i.e. C++, Java, Clojure, JavaScript, etc.) have their own preferred styles. So for Python: new_num rather than newNum (i.e. not camelCase for variables and function names).
Using reference 2
Zen of Python: "Simple is better than complex".
Your while loop is overly complicated by focusing on two objectives, namely: (1) generating fibonacci numbers, and (2) printing fibonacci numbers). From Single Repository Principle we know less is better than more (i.e. objectives).
Simplify by creating code blocks with single rather than multiple objectives.
while True: # objective 1--generating fib numbers
newNum = n1 + n2
fiblist.append(newNum)
n1 = n2
n2 = newNum
if newNum >= 10000:
break
print(fiblist) # objective 2--printing fib numbers
Next, we simplify by improving robustness. Robustness — "Simple objects allow you to focus on the specificities of each task individually and reduces the amount of input/output variables you need to consider at any given time". fiblist is a simple object we can use to replace n1, n2, and new_num as follows:
fiblist[-2] is n1
fiblist[-1] is n2
fiblist[-1] is new_num (after append)
Using robustness the code becomes:
while fiblist[-1] < 10000:
fiblist.append(fiblist[-1] + fiblist[-2])
In order for this to work, we need to initialize fiblist before the while loop to:
fiblist = [0, 1]
Thus with this sequence of simplifications, we obtain the suggested code.
Additional References to be a better Programmer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With