"Do x iterations of the Fibonacci sequence, and display the output."
This exercise was much easier than the first. I was able to complete it without really any research, and used just the Python I learned looking over the various tutorials.
Click to see Solution:
#!/usr/bin/env python
import sys
print "Start"
#Set varIterations to 0 to start
varIterations = None
#Use Try Catch to catch errors
try:
#Enter number of iterations.
#If int(string) fails, python will throw an exception which is caught by the Try.
#Not an elegant way of verifying the input...but it works.
#In the future, I plan to add specific exceptions. In this case, something like except: ValueError should do nicely.
varIterations = int(raw_input("Enter number: "))
except:
print "Try again."
pass
if varIterations:
#The following code is responsible for all the work.
#I manually set the first two values: 0, 1.
#I then loop var1 plus var2, replace var1 with var2, and replace var2 with the result of var1+var2.
#You then display the output x-2 number of times, with x equaling the number of iterations.
#You use x-2 because var1 and var2 are already set.
var1 = 0
var2 = 1
n = 0
if varIterations == 0:
print "End"
if varIterations == 1:
print(var1)
if varIterations >= 2:
print (var1)
print (var2)
varIterations = varIterations - 2
for n in range(0,varIterations):
varWork = var1 + var2
print (varWork)
var1 = var2
var2 = varWork
n+=1
No comments:
Post a Comment