Python code example

#Find Prime Number
# Loop statements may have an else clause
# It is executed when the loop terminates
# But not when the loop is terminated by a break statement
for n in range(2, 200):
    for x in range(2, n):
        if n % x == 0:
            print n, 'equals', x, '*', n/x
        # loop fell through without finding a factor
        print n, 'is a prime number'
import sys
def fib(n):  # write Fibonacci series up to n
     a, b = 0, 1
     while a < n:
         print a,
         a, b = b, a+b
if len(sys.argv) >= 2:
    print "Fibonacci " + sys.argv[1]
from __future__ import with_statement
import sys
if len(sys.argv) >= 2:
   name = sys.argv[1];
print "Open: "+name;
lines ='';
with open(name) as f:
    for line in f:
print lines
#! /usr/bin/env python
import fileinput
import sys
   lines1 = fileinput.input(sys.argv[1])
   lines2 = fileinput.input(sys.argv[2])
   out = []
   list_lines1 = []
   list_lines2 = []
   for line1 in lines1:
   	list_lines1.append(str(line1).replace("\n", ""))
   for line2 in lines2:
   	list_lines2.append(str(line2).replace("\n", ""))
   for line1 in list_lines1:
	if line1  in list_lines2:
		if line1 not in out:
			print line1
except IOError:
   print "I/O error"
#! /usr/bin/env python
import fileinput
import sys
   lines = fileinput.input()
   out = []
   for line in lines:
	if line  not in out:
		s= '%s' % (line[0:len(line)])
		s=s.replace("\n", "")
		print '%s' % (s)
except IOError:
   print "I/O error"
import fileinput
import sys
import os
a= os.popen("cat /etc/hosts")
for line in a.readlines():
	print line
from decimal import *
def pi():
    getcontext().prec = 1000 
    three = Decimal(3)     
    lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
    while s != lasts:
        lasts = s
        n, na = n+na, na+8
        d, da = d+da, da+32
        t = (t * n) / d
        s += t
    return +s
print pi();
import urllib2
import sys
# get http or https
print urllib2.urlopen("").read()
print urllib2.urlopen("").read()
# get with a specific header
req = urllib2.Request("")
req.add_header('Referer', '')
req.add_header('User-Agent', 'python ')
print urllib2.urlopen(req).read()
from HTMLParser import HTMLParser
import httplib
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "Encountered a start tag:", tag
        print ''
    def handle_endtag(self, tag):
        print "Encountered an end tag :", tag
        print ''
    def handle_data(self, data):
        print  data 
# get content
conn = httplib.HTTPConnection("")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print r1.status, r1.reason
data =
# process html
parser = MyHTMLParser();