Python quick start guide

As I bought Raspberry PI I needed to learn some basics of Python. What is so special about Python is that it doesn't use so many parenthesis. Instead it is very important the indentation of the code.

Save the scripts with .py suffix.

Run scripts with $ python

Hello world

Example of printouts


print "Hello World"

count = 100
miles = 1.8
name = "John"
# comment

print count
print miles
print name


Creating list of objects


list = [ 'aaa', 123, 22.3, "bla bla" ]
print list[0]
print list[1]
print list[2]
print list[3]
print list[1:3]
print list[2:]


Map of objects (key-value pairs)


map = {}
map['one'] = "This is one"
map[2] = "This is two"
print map['one']

mapp = { 'name':'john', 'code':1234 }
print mapp['name']
print mapp
print mapp.keys()
print mapp.values()


Basic if-else example


x = 101

if (x == 100):
    print "x=100 - True"
    print "False"


Example of while and for loops


count = 0
while (count < 5):
print 'Count: ', count
count += 1
print count, " is more than 5"

for letter in 'Python':
print 'Current letter: ', letter

fruits = [ 'apple', 'banana', 'mango' ]
for fruit in fruits:
print 'Fruit: ', fruit

for index in range(len(fruits)):
print 'Fruit[', index, ']: ', fruits[index]

Read input arguments

When the script is invoked with additional arguments (like $ python arg1 arg2)


import sys

print "Number of arguments: ", len(sys.argv)
print "Argument list: ", str(sys.argv)

Read user input

Some user intarcations


x = 1
while x == 1:
    num = raw_input("Enter number: ")
    print "You entered: ", num

Show time

Show current timestamp


import time

ticks = time.time()
print "ticks since 1970: ", ticks

localtime = time.localtime(time.time())
print 'current time: ', localtime

Prime numbers

Print prime numbers


for num in range(1,200000):
    for i in range(2,num):
        if num%i == 0:
            # print '%d equals %d * %d' % (num, i, j)
        print num, ' is prime number'

Read file

Example how to read file


f = open("test.txt", "r+")
str =;
print "File name: ",
print "Read: ", str

Write file

Example how to write data to file


import os

print os.getcwd()

# read file
f = open("test.txt", "r+")
str =;
print "File name: ",
print "Read: ", str

# write to file
f = open("test.txt", "wb")
f.write("Python is great")

Creating custom modules

First create a module and define some functions


def sum(a, b):
    return a+b

Then create a script that imports your module


import mylib

x = mylib.sum(1, 2)
print "sum=", x

Creating classes

Create a class Monkey


class Monkey:

    count = 0

    def __init__(self, name, age): = name
        self.age = age
        Monkey.count += 1

    def displayCount(self):
        print "Number of monkeys: %d" % Monkey.count

    def displayMonkey(self):
        print "Name: ",, ", Age: ", self.age

Then import your class and use it:


import MonkeyLib

m1 = MonkeyLib.Monkey("Mark", 2)
m2 = MonkeyLib.Monkey("Fred", 5)

print "Number of monkeys: ", MonkeyLib.Monkey.count

Another example of Employee class (all in one py file)


class Employee:

    empCount = 0

    def __init__(self, name, salary): = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print "Number of employees: %d" % Employee.empCount

    def displayEmployee(self):
        print "Name: ",, ", Salary: ", self.salary

emp1 = Employee("John", 2000)
emp2 = Employee("Lucy", 3500)
print "Total number of employees: ", Employee.empCount
print "---------------------------"

print "-- set attributes--"
emp1.age = 20;
#print "emp1.age=", emp1.age
#del emp1.age # delete attribute

if (hasattr(emp1, 'age') == False):
    setattr(emp1, 'age', 28)
    print "attribute age set: ", emp1.age
    print "get attribute age: ", getattr(emp1, 'age')

delattr(emp1, 'age')

Insert measurement into InfluxDB with Python

To insert a measurement into InfluxDB in Python, you need to write a http client that sends POST request to InfluxDB HTTP API.

Here is piece of python code that initiates http connection with the InfluxDB server, prepares POST request and prints returned HTTP error code.

Remark: InfluxDB returns error code 204 if measurement was successfully inserted.

#!/usr/bin/env python

import httplib

httpServ = httplib.HTTPConnection("", 8086)

stringValue = str(22)
httpServ.request('POST', '/write?db=myDatabase', 'temperature,sensor=T1 value=' + stringValue)

response = httpServ.getresponse()
print response.status