Coconut Catalogue
coconutc.com

4) Python

Introduction

Python is preinstalled in Raspbian. There are 2 version of python available ie. python 2 and python 3. Python 3 is not backward compatible, ie. some commands of python 3 may not work on python 2. To open python got to top left corner raspberry symbol and select for python 3.

Python is an interpreted language ie. it is interpreted line by line.

We can do python coding either in terminal or in python editor. We can use any other editor such as nano or leafpad, we just have to make sure that we save it with extension .py ie. filename.py.

Although python files can be executed easily on python IDE but you can also execute it using linux terminal by using
python filename.py.

Python Coding

Single line comments in python are given by #comment. While multi-line comments are given by '''comment'''.

print("text") is used to print string. We can also use a variable to print containing the string print(variable).

printing.py
text="Dirty"
print("Hello World!")
print(text)
			
Linux Terminal
pi@raspberry:~$
pi@raspberry:~$ ls Desktop
printing.py
pi@raspberry:~$ python Desktop/printing.py
pi@raspberry:~$ Hello World!
Dirty
			

for loop is a very important looping instruction. Its syntax is
for i in range(n): what ever instruction should be included in it have to be indented and is repeated n times. Here i is a variable and its count starts from 0 to n-1.

movie.py
for i in range(5):
	print("Fury")
			
Linux Terminal
pi@raspberry:~$
pi@raspberry:~$ ls Desktop
movie.py
pi@raspberry:~$ python Desktop/movie.py
pi@raspberry:~$ Fury
Fury
Fury
Fury
Fury
			

List is a collection of similar or different data types. They are similar to arrays except that they can store different data types.
listname=[number,"string"].
To access a particular element in list we use listname[n].

python terminal
>>>numbers=[1,'forty seven',34,'sixty seven']
>>>numbers[0]
1
>>>numbers[1]
'forty seven'
			

.append(n) method is used to add a single element to list while .extend([n,m]) method is used to more than 1 element in the list.

python terminal
>>>numbers=[1,34]
>>>numbers
[1,34]
>>>numbers.append(39)
>>>numbers
[1,34,39]
>>>numbers.append('forty four')
>>>numbers
[1,34,39,'forty four']
>>>numbers.extend([94,'eleven'])
>>>numbers
[1,34,39,'forty four',94,'eleven']
			

.pop(n) method is used to pop an element from the list where n denotes the nth element in the list.
.remove(m) method is used to remove m in the list.

python terminal
>>>numbers=[47,34,82,96]
>>>numbers.pop(2)
82
>>>numbers
[47,34,96]
>>>numbers.remove(47)
>>>numbers
[34,96]
			

.insert(location,content) method is used to insert an element in the list at a particular location.

python terminal
>>>numbers=[47,34,82,96]
>>>numbers.insert(2,78)
>>>numbers
[47,34,78,82,96]
			

Iteration of List

for listname in listname: prints all the elements in a list in vertical order when used with print(listname).

python terminal
>>>numbers=[47,34,'eighty two',96]
>>>for numbers in numbers:
	print(numbers)
47
34
78
eighty two
96
>>>
			

Length of List

len function is used to find out the length of the list or a string.

python terminal
>>>name='Jackson'
>>>numbers=[1,'thirteen',45,97]
>>>len(name)
7
>>>len(numbers)
4
>>>
			

IF-ELSE

If-else statement is used as in any other programming language.

python terminal
>>>name='Jackson'
>>>if len(name)>5:
	print('Your name '+name+' is of correct length.')
	 else:
	print('Your name is short.')

Your name Jackson is of correct length.
>>>
			
CAUTION
>>>movies=['a','b','c']
>>>for movies in range(len(movies)):
	print(movies)
0
1
2
			

User defined function

def function_name (arguments): is the syntax of user defined functions in python.

udf.py
>>>def printing(x)
	for i in range(x):
		print(name)
>>>name='semester'
>>>printing(8)
semester
semester
semester
semester
semester
semester
semester
semester
>>>
			

enumerate

enumerate() is used as follows:

udf.py
>>>name=['Stauffenberg','Wilson','Jackson','George']
>>>list(enumerate(name))
[(0,'Stauffenberg'),(1,'Wilson'),(2,'Jackson'),(3,'George')]
>>>list(enumerate(name,start=2))
[(2,'Stauffenberg'),(3,'Wilson'),(4,'Jackson'),(5,'George')]
			

Python Libraries

Python Libraries contains following:-

  1. Built-in Functions

  2. Python Standard Libraries

  3. Third party Libraries

Built in Functions

Built in Functions

Python Standard Libraries

https://docs.python.org/3/library/
Require importing the module at the start of the program.

Built in Functions

To update libraries type following in Linux Terminal:
$ sudo apt-get update
To install a particular library type following in Linux Terminal:
$ sudo apt-get install python pi-camera

Third Party Libraries

https://pypi.python.org/pypi
To install third party libraries we need to install pip software by following command in linux terminal:
$ sudo apt-get install python-pip
To install third party library such as simplejson using pip software type following in linux terminal.
$ sudo pip install simplejson

Shapes in Python 2

shape1
shapeone.py
import turtle
import time

window=turtle.Screen()
window.bgcolor("grey")
drawing=turtle.Turtle()
drawing.shape("turtle")
drawing.color("red")
drawing.speed(5)
drawing.pensize(10)
for j in range(36):
	for i in range(4):
		drawing.forward(100)
		drawing.right(90)
	drawing.right(10)
			
shape2
shapetwo.py
import turtle
import time

col=["green","blue","red","yellow"]

window=turtle.Screen()
window.bgcolor("grey")
drawing=turtle.Turtle()
drawing.shape("turtle")
drawing.speed(5000)
drawing.pensize(9)
for k in range(4):
	drawing.color(col[k])
	for j in range(36):
		for i in range(4):
		drawing.forward(50+k*40)
		drawing.right(90)
		drawing.right(10)
			
shape3
shapethree.py
import turtle
import time

window=turtle.Screen()
window.bgcolor("black")
drawing=turtle.Turtle()
drawing.shape("arrow")
drawing.speed(5000)
drawing.pensize(1)

def pent(length,size):
 x=length
 for i in range(5):
	 drawing.forward(length)
	 if size>0:
	pent(length/3,size-1)
	 drawing.backward(x)
	 drawing.right(72)
pent(120,4)
			

×