PLAYING WITH PYTHON
Learning Outcomes:
- Defining functions
- Recursive function
- using Graphics
- Using if else statements and for loops
Aim of the program
Creating a program to represent Fibonacci sequence graphically (Fibonacci spiral) .
#Febonacci sequence
The Fibonacci sequence, also known as Fibonacci numbers, is defined as the sequence of numbers in which each number in the sequence is equal to the sum of two numbers before it. The Fibonacci Sequence is given as:
Fibonacci Sequence = 0, 1, 1, 2, 3, 5, 8, 13, 21, ….
This is the graphical representation of Fibonacci sequence
If you sum the squares of any series of Fibonacci numbers, they will equal the last Fibonacci number used in the series times the next Fibonacci number. This property results in the Fibonacci spiral, based on the following progression and properties of the Fibonacci series:
12 + 12 + 22 + 32 + 52 = 5 x 8
Let’s start simulating..
STEP-1 : writing the program
***Import turtle (graphics module in python)
-First defining a function that gives the nth Fibonacci number.
-Second: we should define another function that will basically draw a square according to the length of side of the square.
-Third: defining the main function (the one we will call to execute the program). In this main function we will use for loop and give a predefined range for the terms in Fibonacci sequence.
STEP-2 : if we want to draw the Fibonacci spiral we have to find a pattern.
Pattern is –
1) Draw a square with length as nth Fibonacci term.
2) After drawing, turn the pointer 90 degrees left, and move forward with prev length
3) Repeat step 2
**Repeat this in a loop.
[Note: in python turtle(graphics module) after drawing the square the pointer automatically turns left.]
**so there is no requirement to turn left in step two.
but it is required in step three.**
CODE:::
def febo(n):
if n < 3:
return 1
else:
return febo(n - 1) + febo(n - 2)
from turtle import Turtle
t = Turtle()
t.setheading(180)
def drawsquare(length):
t.down()
for count in range(4):
t.forward(length)
t.left(90)
def main():
for i in range(1, 20):
length = febo(i)
print(length)
drawsquare(length)
t.forward(length)
t.left(90)
t.forward(length)
#calling the main function
main()
OUTPUT:::
This will go on till 20th term of febonacci series.
Comments
Post a Comment