Raspberry_Pi_Education_Manual

Notes:

Just add Raspberry Pi

So, the same question. What are the factors of all the numbers from 1 to 50? Before you can start programming, you will need to start up an editor so that you can type in instructions to the Raspberry Pi.

Open a new editing window from the File menu in IDLE. This will allow you to work in the IDLE text editor.

Tip...

Open up the IDLE editor as before, but this time use the File menu to select a new editing window. This is no longer the Python shell, but a text editor. You can type in your program but it won’t be interpreted by your Raspberry Pi until you tell it to “Run”. This text editor has been tweaked to make it very good for writing Python, just as a word processor has been tweaked to check your spelling and grammar. In this window, type exactly what you see here, including the correct spaces before each line and all in lowercase. You can use Tab to indent your lines in the IDLE editor, and it will convert these to spaces.

The indent of four spaces should appear automatically after the line ending with a colon (:). The indent of eight spaces will appear after the second line ending with a colon.

for number in range (1, 51):

print (number, ":" , end= " " ) for divisor in range (1, number+1): if number%divisor == 0: print (divisor, end= " " ) print ()

Tip...

This program uses two loops, “range”, “print”, “if”, “%” and “==”, and two variables to hold data. The “range” function will generate the numbers from the first to one below the last; in this case, 1 to 50. The “%” operator will give the remainder after dividing the two variables. Also, notice how “==” is used rather than just “=”. This is because, on a computer, setting a variable to a number is different to comparing the equality of numbers. Using “==” makes it clear that you want to compare the numbers for equality. The print function normally ends the line with a carriage return (the same as when you pressed the Return key). To stop this, you can tell the print function what you want at the end. In this program, we are telling “print” to put a space character at the end of the line instead. “print()” will end the line to give us a new row for the next answer.

In computer maths, the following symbols are used rather than what you might be used to: * for multiply,

instead of x / for divide, instead of ÷

% for modulo, instead of / or mod .

Experiments in Python

80

Made with FlippingBook flipbook maker