Home of RF and Wireless Vendors and Resources

One Stop For Your RF and Wireless Need

Python Programming Tutorial-Page2

Refer following pages to learn complete Python language tutorial.
Python tutorial page1
Python tutorial page2
Python tutorial page3
Python tutorial page4
Python tutorial page5
Python tutorial page6

pass statement

Sometimes you will need to specify an empty block of code
if name in namelist:
# Not implemented yet (or nothing)
pass is a "no-op" statement
It does nothing, but serves as a placeholder for statements.

Long Lines

Sometimes you get long statements that you want to break across multiple lines
Use the line continuation character (\)
if product=="game" and type=="pirate memory" \
and age >= 4 and age <= 8:
print "I'll take it!"
However, not needed for code in (), [], or {}

Basic Datatypes

•  Python only has a few primitive types of data
•  Numbers
•  Strings (character text)


Python has 5 types of numbers
Long Integers
Floating point
Complex (imaginary numbers)

Booleans (bool)

Two values: True, False
a = True
b = False
Evaluated as integers with value 1,0
c = 4 + True # c = 5
d = False
if d == 0:
print "d is False"

Integers (int)

Signed integers up to machine precision
a = 37
b = -299392993
c = 0x7fa8 # Hexadecimal
d = 0253 # Octal
Typically 32 bits

Long Integers (long)

Arbitrary precision integers
a = 37L
b = -126477288399477266376467L
Integers that overflow promote to longs

Integer Operations

+ Add
- Subtract
* Multiply
/ Divide
// Floor divide
% Modulo
** Power
<< Bit shift left
>> Bit shift right
& Bit-wise AND
| Bit-wise OR
^ Bit-wise XOR
~ Bit-wise NOT
abs(x) Absolute value
pow(x,y[,z]) Power with optional modulo (x**y)%z
divmod(x,y) Division with remainder

Integer Division

Classic division (/) - truncates
>>> 5/4
Floor division (//) - truncates (same)
>>> 5/4
Future division (/) - Converts to float
>>> from __future__ import division
>>> 5/4

If truncation is intended, use //

Use a decimal or exponential notation
a = 37.45
b = 4e5
c = -1.345e-10
Represented as double precision using the native CPU representation (IEEE 754)
17 digits of precision
Exponent from -308 to 308

Be aware that floating point numbers are inexact when representing decimal values.
>>> a = 3.4
>>> a
This is not Python, but the underlying floating point hardware on the CPU.

Floating point operators

+ Add
- Subtract
* Multiply
/ Divide
% Modulo (remainder)
** Power
pow(x,y[,z]) Power with optional modulo (x**y)%z
divmod(x,y) Division with remainder
Additional functions are in math module
import math
a = math.sqrt(x)
b = math.sin(x)
c = math.cos(x)
d = math.tan(x)
e = math.log(x)

Converting Numbers

Type name can be used to convert
a = int(x) # Convert x to integer
b = long(x) # Convert x to long
c = float(x) # Convert x to float

>>> a = 3.14159
>>> int(a)
Also work with strings containing numbers
>>> a = "3.14159"
>>> float(a)
>>> int("0xff",16) # Optional integer base


Written in programs with quotes
a = "Yeah but no but yeah but..."

String Escape Codes,Representation,Operations,methods

String Escape Codes are as follows:
In quotes, standard escape codes work
'\n' Line feed
'\r' Carriage return
'\t' Tab
'\xhh' Hexadecimal value
'\"' Literal quote
'\\' Backslash

Strings are an ordered sequence of bytes (characters).
They are stored as 8-bit data (ASCII).

Strings work like an array : s[n]
a = "Hello world"
Slicing/substrings : s[start:end]
d = a[:5] # d = "Hello"
Concatenation (+)
a = "Hello" + "World"

Length (len)
>>> s = "Hello world"
>>> len(s)

Membership test (in)
>>> 'e' in s
Replication (s*n)
>>> s = "Hello"
>>> s*5

String Methods

Strings have "methods" that perform various operations with the string data.
Stripping any leading/trailing whitespace
t = s.strip()
Case conversion
t = s.lower()
t = s.upper()
Replacing Text
t = s.replace("Hello", "Hallo")

More String Methods

s.endswith(suffix)    # Check if string ends with suffix
s.find(t)    # First occurrence of t in s
s.index(t)    # First occurrence of t in s
s.isalpha()    # Check if characters are alphabetic
s.isdigit()    # Check if characters are numeric
s.islower()    # Check if characters are lower-case
s.isupper()    # Check if characters are upper-case
s.join(slist)    # Joins lists using s as delimeter
s.lower()    # Convert to lower case
s.replace(old,new)    # Replace text
s.rfind(t)    # Search for t from end of string
s.rindex(t)    # Search for t from end of string
s.split([delim])    # Split string into list of substrings
s.startswith    # Check if string starts with prefix
s.strip()    # Strip leading/trailing space
s.upper()    # Convert to upper case

String Mutability

Strings are "immutable" (read only)
Once created, the value can't be changed
>>> s = "Hello World"
>>> s[1] = 'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> All operations and methods that manipulate string data always create new strings

String Conversions

To convert any object to string
s = str(obj)
Produces the same text as print
Actually, print uses str() for output
>>> x = 42
>>> str(x)

String Splitting

Strings often represent fields of data
To work with each field, split into a list
>>> line = 'GOOG 100 490.10'
>>> fields = line.split()
>>> fields
['GOOG', '100', '490.10']


A array of arbitrary values
names = [ "Elwood", "Jake", "Curtis" ]
nums = [ 39, 38, 42, 65, 111]
Can contain mixed data types
items = [ "Elwood", 39, 1.5 ]
Adding new items (append, insert)
items.append("that") # Adds at end
items.insert(2,"this") # Inserts in middle
Concatenation : s + t
s = [1,2,3]
t = ['a','b']
s + t ---> [1,2,3,'a','b']

Lists are indexed by integers (starting at 0)
names = [ "Elwood", "Jake", "Curtis" ]
names[0] "Elwood"
names[1] "Jake"
names[2] "Curtis"
Negative indices are from the end
names[-1] "Curtis"
Changing one of the items
names[1] = "Joliet Jake"

More List Operations

Length (len)
>>> s = [ "Elwood", "Jake", "Curtis" ]
>>> len(s)

Membership test (in)
>>> 'Elwood' in s
>>> 'Britney' in s
Replication (s*n)
>>> s = [1,2,3]
>>> s*3

List removal is done as follows:
Removing an item
Deleting an item by index
del names[2]

File Input and Output

Opening a file
f = open("foo.txt","r") # Open for reading
g = open("bar.txt","w") # Open for writing
To read data line = f.readline() # Read a line of text
data = f.read() # Read all data
To write text to a file
g.write("some text")
To print to a file
print >>g, "Your name is", name

Looping over a File

Reading a file line by line
f = open("foo.txt","r") # Open for reading
for line in f:
# Process the line

for line in open("foo.txt","r") :
# Process the line
... This reads all lines until you reach the end of the file

Type Conversion

In Python, you must be careful about converting data to an appropriate type
x = '37' # Strings
y = '42'
z = x + y # z = '3742' (concatenation)
x = 37
y = 42
z = x + y # z = 79 (integer +)
This differs from Perl where "+" is assumed to

Simple Functions

Use functions for code you want to reuse
def sumcount(n):
total = 0
while n > 0:
total += n
n -= 1
return total
Calling a function
a = sumcount(100)
A function is just a series of statements that perform some task and return a result

Library Functions

Python comes with a large standard library
Library modules accessed using import
import math
x = math.sqrt(10)

import urllib
u = urllib.urlopen("http://www.python.org/index.html")
data = u.read()

Exception Handling

Errors are reported as exceptions
An exception causes the program to stop
>>> f = open("file.dat","r")
Traceback (most recent call last):
File "", line 1, in
IOError: [Errno 2] No such file or directory: 'file.dat'
>>> For debugging, message describes what happened, where the error occurred, along with a traceback.

dir() function

Useful for exploring, inspecting objects, etc.
dir(obj) returns all names defined in obj
>>> import sys
>>> dir(sys)
dir() will also tell you what methods/attributes are available on an object.
>>> a = "Hello World"
>>> dir(sys)


Share this page

Translate this page