Introduction to Python

 

 

­­

Tutorials:

 

·       http://www.greenteapress.com/thinkpython/

·       http://heather.cs.ucdavis.edu/~matloff/python.html

·       http://it-ebooks.info/book/304/

·       http://docs.python.org/3.3/tutorial/

·       http://docs.python.org/3/library/

 

 

 

 

String:

#! /usr/bin/python

# Example 1

fruit = 'banana'
index = 0
while index < len(fruit):
    letter = fruit[index]
    print letter
    index = index + 1

# Example 2

print ' '
for char in fruit:
    print char

# Example 3

print ' '
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
    print letter + suffix

# Example 4

print ' '
print fruit[2:5]
print fruit[2:]
print fruit[:5]

# Example 5

print ' '
count = 0
for letter in fruit:
    if letter == 'a':
       count = count + 1
print count


# Example 6

print ' '
print fruit.upper()

# Example 7

print ' '
print fruit.find('na')
print fruit.find('na', 3)


# Example 8

print ' '
def in_both(word1, word2):
    for letter in word1:
       if letter in word2:
           print letter

in_both('apples', 'oranges')

 

 

List:

 

#! /usr/bin/python
 

# Example 1

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print c

 

# Example 2

print
c = a*3
print c
c.sort()
print c

print
a.append('x')
print a

print
a.extend(b)
print a

# Example 3

print
t = ['a', 'b', 'c', 'd', 'e', 'f']
t[1:3] = ['x', 'y']
print t

print
t.remove('d')
print t
del t[1:3]
print t

# Example 4

print
first = 'Hussein'
f = list(first)
print f

print
last = 'Abdel-Wahab'
delimiter = '-'
l = last.split(delimiter)
print l
j = delimiter.join(l)
print j
 

 

 

Dictionary:

 

#! /usr/bin/python
 

phonebook = dict()
phonebook ['ajay'] = '683-4532'
phonebook ['wahab'] = '683-4512'
phonebook ['maly'] = '683-4522'
print phonebook
print phonebook['wahab']
print len(phonebook)


 

Tuple:

 

#! /usr/bin/env python    This is more general
 

addr = 'wahab@cs.odu.edu'
uname, domain = addr.split('@')
print uname
print domain

print
t = divmod(7, 3)
print t
quot, rem = divmod(7, 3)
print quot
print rem

 

 

 

Random:

 

#! /usr/bin/env python
import random

for i in range(10):
    x = random.randint(1, 100)
    print x

print
list = [1, 2, 3, 7, 8, 9]
c = random.choice(list)
print c


 

 

 

Math:

 

#! /usr/bin/python
def gcd(a, b):
    "greatest common divisor"
    while a != 0:
       a, b = b%a, a # parallel assignment
    return b
 

print
print gcd.__doc__
print gcd(12, 20)
print
import math
print math.sqrt(88)
print math.sin(2.5)
 

 

File:

 

#! /usr/bin/python

 

# Example 1
fout = open('output.txt', 'w')
line1 = "Hussein Abdel-Wahab\n"
fout.write(line1)
line2 = "ODU\n"
fout.write(line2)
fout.close()

print
try:
    fin = open('output.txt')
    for line in fin:
       print line, #, no newline
    fin.close()
except:
    print 'Something went wrong.'


# Example 2
import sys
print
def linecount(filename):
    count = 0
    for line in open(filename):
       count += 1
    return count
print linecount('output.txt')

#print linecount(sys.argv[1])

# Example 2
import sys

print
# reads in the text file whose name is specified on the command line,
# and reports the number of lines and words
def checkline():
    global l
    global wordcount
    w = l.split()
    wordcount += len(w)

wordcount = 0
f = open('files.py')
# f = open(sys.argv[1])
flines = f.readlines()
linecount = len(flines)
for l in flines:
    checkline()
print linecount, wordcount

 

System:

 

#! /usr/bin/python

import os
os.system('cat systems.py')
 

print ' '
fp = os.popen(‘ls –l’)
res = fp.read()
print res

import sys
print ' '
print 'what is your info? (type CTRL-D when done)'
w = sys.stdin.readlines() # keyboard input, ctrl-d to end
print w

 

import time
print ' '
print time.ctime() # translate that to English

import commands
print ' '
print commands.getoutput('ypcat passwd | egrep ":13:"')

import re
for line in re.split('\n',commands.getoutput('ypcat passwd')):
    if re.search(':13:',line):
       print line.split(':')[0], ': ', line.split(':')[4]
 

 

Class:

 

#! /usr/bin/python
class Stack:
    "A stack data structure"
    def __init__(self): # constructor
       self.items = []
    def push(self, x):
       self.items.append(x) # the sky is the limit
    def pop(self):
       x = self.items[-1] # what happens if its empty?
       del self.items[-1]
       return x
    def empty(self):
       return len(self.items) == 0 # Boolean result

print
x = Stack()
print x.empty()
x.push(1)
print x.empty()
x.push(2)
x.push("hello")
print x.pop()
print x.items
 

 


Socket:

 

Server:

 

#! /usr/bin/env python
import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ''
port = int(sys.argv[1])
s.bind((host, port))

s.listen(1)
conn, addr = s.accept()
print 'client is at', addr

while (1):
    data = conn.recv(1000000)
        if not data:           # if end of data, leave loop
                break
        print 'received', len(data), 'bytes: ', data
    conn.send(data)

conn.close()
 

 

Client:

 

#! /usr/bin/env python
import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = sys.argv[1] # server address
port = int(sys.argv[2]) # server port
s.connect((host, port))

while(1):
    print 'type a line (type CTRL-D when done)'
    line = sys.stdin.readline()    # keyboard input, ctrl-d to end
    if not line:                   # if end of data, leave loop
       break
    s.send(line)
    data = s.recv(1000000)         # read up to 1000000 bytes
    print 'received', len(data), 'bytes: ', data

s.close()
 

­