Raspberry_Pi_Education_Manual

Notes:

The Fibonacci Sequence

Let’s write another program to work out a famous mathematical sequence. Each number in the Fibonacci Sequence is simply the previous two numbers added together; starting with 0 and 1. Create a new file using IDLE and name it “ Fibonacci.py ”.

The following will calculate the numbers in the sequence up to the first value that is larger than 100.

first = 0 print (first, end= " " ) second = 1 while (first < 100):

print (second, end= " " ) third = first + second first = second second = third

And the result is:

0 1 1 2 3 5 8 13 21 34 55 89 144

This program should be easier to follow than the first. It has a single loop but, instead of using “for”, it uses “while”. This loop will continue while the variable “first” is less than 100. You should be able to see that “144” is displayed because it is the first value that passed this test. See what happens when you change “first < 100” to “second < 100”.

The number 0

In almost all computing, number counting begins with 0. In the real world, it is common to count from 1. This can be very confusing until you get used to it – and even more confusing if you start using one of the few computer languages that does count from 1. The history of counting from 0 in computing stems from indexing into memory. You can say the first item in memory is a distance 0 from the start of its memory. The languages that are 1-based compensate for this automatically. Python is 0-based. This can lead to even more confusion at the other end of your counted range. If you start at 0 and need 10 consecutive numbers, the last number will be 9. The “range()” function is not generating numbers from the first to the last number, it is starting at the first number and giving you the consecutive values after that. That is why in the factors example, the program appears to count from 1 to 51. Start at 1 and give me 51 consecutive numbers. Here is a way to iterate (i.e. count) through what the range function is generating.

>>> [ x for x in range (0, 10) ] # 10 numbers starting at 0 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [ x for x in range (1, 51) ] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

Experiments in Python

82

Made with FlippingBook flipbook maker