-
Fundamentals of PYTHON



Home Page



           

Introduction
Basic KIT
IDE
DOC/Links
Serial COM
How to run a python program
Basic Linux Commands
Operators
Arithmetic Operators
Comparison Operators
Assignment Operators
Bitwise Operators
Logical Operators
Membership Operators
Identity Operators
Operators Precedence
Numbers and Strings
print
input (Input number)
raw_input
(Input string)
Input data from keyboard
if... elif... else
Lists
Functions
File
Creating graphical user interfaces



-
Introduction


What is Python ?
The answer is (directly from python.org):
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.
The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.


Versions of Python
Our first Python program



-
Basic KIT for developing in PYTHON


IDE

I'm using Python on XUBUNTU and the graphics interface is XFCE, my IDE is: SPE (Stani's Python Editor).
From Ubuntu Software Center you must install: SPE

A simple IDE is available directly from here: https://www.python.org/getit/
From Ubuntu Software Center you must install: python idle


DOC/Links

I suggest to see this link




Serial COM

For drive the Serial COM I suggest:

pySerial
http://pyserial.sourceforge.net/index.html

Now see also (starting with V3.0):

See also:

Old pages (up to V2.7):




How to run a Python program

There are two possibility:
  • Run Python Interpreter
  • Run a Python file
Run Python Interpreter
From the terminal, write:
python
You must see something like below:
Python 2.7.6 (default, Jun 22 2015, 18:00:18)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Now everything you write is immediately executed.
Try to write this sequence of statements:

ciao = ((4*4)/2)
print ciao

You must see something like below:
>>> ciao = ((4*4)/2)
>>> print ciao
8
>>>
 
Run a Python file
From the terminal, write:
python name_of_your_python_file.py


Some basic Linux commands

For know the release of LINUX installed into the PC use the commands below listed.

cat /etc/issue
or
lsb_release -a
May be helpful to know which kernel version is running on our Ubuntu. This one sees with:
uname -r
For know the USB port in use on your PC use this command:
lsusb
or
dmesg
Remember that before to use your serial port you must change the permission on it.
To do this use the commands below.

cd /dev
if your serial port is ttyUSB0 use this command:
chmod 777 ttyUSB0
Normally the device are here:
/dev
and the USB/RS232, normally, is: ttyUSB0 (if you has just one)

See here where there is a list of Linux commands.


UP



-
Operators


The basic operators are:
+  -  /  *
assignment =
comparisons ==, <, >, ! =, <>, <=, >=

modulo % operator, returns the integer remainder of the division, see below.

Using two multiplication symbols ** makes a power relationship.

example
valint = 2
valint = valint ** 3
valfloat = 3.3
valfloat = valfloat / 2
print "valint: ", valint
print "valint: %d" % valint
print "valint: %d" % valfloat


Python supports concatenating strings using the addition operator:
helloworld = "Ciao" + " " + "Mondo"

Python also supports multiplying strings to form a string with a repeating sequence:
lotsofhellos = "hello" * 10

Lists can be joined with the addition operators:
pari_numbers = [2,4,6,8]
dispari_numbers = [1,3,5,7]
all_numbers = dispari_numbers + pari_numbers


Arithmetic Operators - See the example here.


Comparison Operators
- See the example here.


Assignment Operators - See the example here.


Bitwise Operators - See the example here.


Logical Operators - See the example here.


Membership Operators - See the example here.


Identity Operators - See the example here.


Operators Precedence - See the example here.




UP


-
Numbers and Strings


Numbers

Python supports three types of numbers - integers, floating point numbers and complex numbers.

varint = 10
varfloat = 10.5
myfloat = float(7)

example
ciao = ((4*4)/2)
print ciao

Strings

mystring = 'hello'
mystring = "hello, don't worry, python is easy"

Simple operators can be executed on numbers and strings:

one = 1
two = 2
three = one + two

example
one = 10
two = 3
three = one + two
print three

hello = "hello"
world = "world"
helloworld = hello + " " + world

example
mystring = "hello"
myfloat = 10.0
myint = 20

# testing code
if mystring == "hello":
    print "String: %s" % mystring
if isinstance(myfloat, float) and myfloat == 10.0:
    print "Float: %d" % myfloat
if isinstance(myint, int) and myint == 20:
    print "Integer: %d" % myint


Convert a Number in a String


numer = 3.14
string1 = str(number)



Number of element in the String

The method:
len(string)
returns the number of elements in the list.


example

#!/usr/bin/python


list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']

print "First list length : ", len(list1);
print "Second list length : ", len(list2);



String Methods
  • s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
  • s.strip() -- returns a string with whitespace removed from the start and end
  • s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes
  • s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
  • s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
  • s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
  • s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
  • s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc



String Slices

The "slice" syntax is a handy way to refer to sub-parts of sequences -- typically strings and lists.
The slice string[start:end] is the elements beginning at start and extending up to but not including end.  Suppose we have pippo = "12345"

Remeber that:
tring:   12345
pointer: 01234

example
>>> pippo = "12345"
>>> print pippo[1:2]
2
>>> print pippo[1:3]
23
>>> print pippo[0:3]
123
>>>


String %

Python has a printf()-like facility to put together a string.
The % operator takes a printf-type format string on the left (%d int, %s string, %f/%g floating point), and the matching values in a tuple on the right (a tuple is made of values separated by commas, typically grouped inside parenthesis):


example
>>> text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
>>> print text
3 little pigs come out or I'll huff and puff and blow down
>>>


i18n Strings (Unicode)

Regular Python strings are not unicode, they are just plain bytes.
To create a unicode string, use the 'u' prefix on the string literal:


example
>>> ustring = u'A unicode \u018e string \xf1'
>>> print ustring
A unicode Ǝ string ñ
>>>


UP



-
print


print is an instruction for print on screen a variable, a text, etc.

example
x = 3.14
t = 'x =', x
print t

example
a=54
print "The value of a is:", a+1

example
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print s

example
Ciao = 'CIAO, world'
CiaoCiao = repr(Ciao)
print CiaoCiao

example
for x in range(1, 11):
    print repr(x).rjust(2), repr(x*x).rjust(3),
    # Note trailing comma on previous line
    print repr(x*x*x).rjust(4)


for x in range(1,11):
    print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)


example

mystring = "hello"
myfloat = 10.0
myint = 20
if mystring == "hello":
    print "String: %s" % mystring
if isinstance(myfloat, float) and myfloat == 10.0:
    print "Float: %d" % myfloat
if isinstance(myint, int) and myint == 20:
    print "Integer: %d" % myint

UP




-
input


input is used for input numeric data from console
.

example
a=input("Insert NUMBER: ")
print a


example
# Input numerical data from consolle
count = 0
total = 0
markslist = list()

while count<= 3:
    newmark = input("Input mark out od 10 (" + str(count) + ") ")  # Inut data from keyboard
    markslist.append(newmark)
    total = total + newmark
    count = count + 1
   
print "count = ", count
print "total = ", total 
print "Last newmark = ", newmark
print "markslist = ", markslist



UP



-
rav_input

raw_input is used for input string from keyboard

example
Val = raw_input("Write your name: ")
print Val

UP



-
Input data from keyboard


# Input numerical data from keyboard
count = 0
total = 0
markslist = list()

while count<= 3:
    newmark = input("Input mark out od 10 (" + str(count) + ") ")  # Inut data from keyboard
    markslist.append(newmark)
    total = total + newmark
    count = count + 1
   
print "count = ", count
print "total = ", total 
print "Last newmark = ", newmark
print "markslist = ", markslist

# Input string from keyboard
Val = raw_input("Write your name: ")
print Val

UP



-
if... elif... else


if comparison statement:
     instructions
ifif comparison statement:
     instructions

else:
     instructions



example
a=raw_input ("Come ti chiami ? ")
if a == "Enrico":
    print "Ciao", a
else:
    print "Non ti conosco", a

example
a=input ("Password ? ")
if a == 1234:
    print "PW OK", a
else:
    print "PW FAIL", a

example
  mood = "terrible"
  speed = 110
  if speed >= 80:

    print 'License and registration please'
    if mood == 'terrible' or speed >= 100:
      print 'You have the right to remain silent.'
    elif mood == 'bad' or speed >= 90:
      print "I'm going to have to write you a ticket."
      write_ticket()
    else:
      print "Let's try to keep it under 80 ok?"

See:
UP



-
FOR and IN


Python's for and in constructs are extremely useful, and the first use of them we'll see is with lists.
The for construct:
for var in list
is an easy way to look at each element in a list (or other collection).

example
#!/usr/bin/python

squares = [1, 4, 9, 16]
sum = 0
for num in squares:
        sum += num
print sum

example
#!/usr/bin/python

list = ['mamma', 'padre', 'cane']
if 'mamma' in list:
    print 'Here is ' + list[0]



range
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy.

example
#!/usr/bin/python

## print the numbers from 0 through 9
for i in range(10):
        print i

pi@rpi1 ~/PY $ python prova.py
0
1
2
3
4
5
6
7
8
9
pi@rpi1 ~/PY $

example
#!/usr/bin/python

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
        print i, a[i]

pi@rpi1 ~/PY $ python prova.py
0 Mary
1 had
2 a
3 little
4 lamb
pi@rpi1 ~/PY $


while
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

while expression:
   statement(s)


example
#!/usr/bin/python

count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

print "Goodbye!"



UP



-
LISTs



Lists are very similar to arrays.
They can contain any type of variable, and they can contain as many variables as you wish.

List literals are written within square brackets [ ].
Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.

Suppose that:
colors = ['green', 'white', 'red']
print colors[0]    ## green
print colors[2]    ## white
print len(colors)  ## red

colors ----> green  white  red
index ----->   0      1     2

Is not possible copy a list in a string.
string = colors <---- is not possible.



example

mylist = []

mylist.append(10)
mylist.append(20)
mylist.append(30)
print(mylist[0]) # prints 10
print(mylist[1]) # prints 20
print(mylist[2]) # prints 30

# prints out 10,20,30
for x in mylist:
    print x

List Methods

list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.index(x)
Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x)
Return the number of times x appears in the list.

list.sort()
Sort the items of the list, in place.

list.reverse()
Reverse the elements of the list, in place.


UP



-
Functions


# Define a function
def vistxt(testo):
    print "Received: ", testo

# Call function vistxt
vistxt("Enrico")

UP



-
File


Python provides basic functions and methods necessary to manipulate files by default. You can do your most of the file manipulation using a file object.

Before you can read or write a file, you have to open it using Python's built-in open() function.
This function creates a file object, which would be utilized to call other support methods associated with it.


Syntax:
file_object = open(file_name [, access_mode][, buffering])

access_mode: determines the mode in which the file has to be opened.
A complete list of possible values is given below in the table. This default file access mode is read (r).


buffering: If the buffering value is set to 0, no buffering will take place.
If the buffering value is 1, line buffering will be performed while accessing a file.
If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size.


Here is a list of the different access_modes of opening a file.


Modes    Description
r        Opens a file for reading only.
            The file pointer is placed at the beginning of the file.

rb        Opens a file for reading only in binary format.
            The file pointer is placed at the beginning of the file.

r+        Opens a file for both reading and writing.
            The file pointer will be at the beginning of the file.

rb+        Opens a file for both reading and writing in binary format.
            The file pointer will be at the beginning of the file.

        Opens a file for writing only.
            Overwrites the file if the file exists.
            If the file does not exist, creates a new file for writing.

wb        Opens a file for writing only in binary format.
            Overwrites the file if the file exists.

w+        Opens a file for both writing and reading.
            Overwrites the existing file if the file exists.
            If the file does not exist, creates a new file for reading and writing.

wb+       Opens a file for both writing and reading in binary format.
            Overwrites the existing file if the file exists.

a         Opens a file for appending.
            The file pointer is at the end of the file if the file exists.
            If the file does not exist, it creates a new file for writing.

ab        Opens a file for appending in binary format.
            If the file does not exist, it creates a new file for writing.

a+        Opens a file for both appending and reading.
            The file pointer is at the end of the file if the file exists.
            If the file does not exist, it creates a new file for reading and writing.

ab+        Opens a file for both appending and reading in binary format.
            The file pointer is at the end of the file if the file exists.
            If the file does not exist, it creates a new file for reading and writing.


example
#!/usr/bin/python

# Echo the contents of a file
f = open('prova.py', 'rU')
for line in f:   ## iterates over the lines of the file
  print line,    ## trailing , so print does not add an end-of-line char
                 ## since 'line' already includes the end-of line.
f.close()


The file object attributes


Attribute        Description
file.closed      Returns true if file is closed, false otherwise.
file.mode        Returns access mode with which file was opened.
file.name        Returns name of the file.
file.softspace   Returns false if space explicitly required with print, true otherwise.


UP



-
Creating graphical user interfaces


Python is a very powerful programming language and allows to reduce by one third compared to Java code written. In the creation of graphical user interfaces is usually written a lot of code so Python allows us to be more productive. For writing graphical user interfaces, Python provides us with several roads. There are in fact, different libraries used and almost all multiplatform, see the link below.
http://wiki.python.org/moin/GuiProgramming

LINK

http://wiki.python.org/moin/GuiProgramming
http://www.blackbirdblog.it/programmazione/python/gui-con-python (in Italian language)





Home Page