If you are new to programming with Python then you might have a look at the “Welcome To CircuitPython” guide by Adafruit. The chapter “How do I learn Python?” has links to guides for every level of experience.
Another guide “Getting Started with Raspberry Pi Pico and CircuitPython” is dedicated to programming “Pico” boards with CPy. The chapter “NeoPixel LEDs” is very helpful for this workshop.
These guides can also be downloaded from the assets
directory.
Python does not use any explicit syntactic brackets ( like begin
and end
, or {
and }
) to delimit compound statements.
That’s why indentation (usually by 4 spaces) is used to group statements.
Python does have most of the usual control structures.
But you need to terminate the ’test’ with a colon :
.
1# IF statement
2if (a == b):
3 x = y
4elif (b == c):
5 x = z
6else:
7 z = x +y
8
9# WHILE statement
10i = 0
11while (i < 10):
12 i += 1
13
14# FOR statement
15for j in range(10):
16 print(j)
The same is true for function definitions.
Put the name and all parameters onto the first line and terminate the line with a colon :
.
Then you need to indent all statements of the function body.
The function definitions ends, when you outdent to the level of the def
keyword.
1# Function defintion
2def fname(x, y, z):
3 return x * y * z
4
5print( fname(2, 3, 5) )
Python does have all the usual data types, like integers, floats and strings.
Some conversions are done implicitly. Others need to be carried out explicitly by calling a function.
1a, b = 5, 7
2x, y = 9.7, 6.5
3z = float( a + b )
4c = int( x / y )
5s = "my "
6t = " know"
7r = "ledge"
8print(z, c, s+t+r)
The basic data structures of Python are lists, dictionaries, and tuples:
1# LISTS have indices that are integers and can be used as ARRAYS
2# delimiters are [ and ]
3a = [ 1, 2, 3, ]
4rgb = [ 0xff, 0xcc, 0xd8 ]
5b = [ 'a', 12, 3.14, [], rgb ]
6print( a[1], b[4] )
1# DICTIONARIES are similar to LISTS,
2# except the indices are strings (or any other type)
3# delimiters are { and }
4word = {}
5word['en'] = 'book'
6word['de'] = 'buch'
7word['fr'] = 'livre'
8words = { 'one': 'eins', 'two': 'due', 'three': 'trois', }
1# TUPLES are an immutable sequence of values
2# delimiters are ( and )
3t = ( 1, 2, 3, 4, 5 )
4print( t[2] )