Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Workshop programs

637 views

Published on

python sample programs

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Workshop programs

  1. 1. Python examples Compile Python program:python filename.py First.py#! /usr/bin/env python#Above is valid only if you are using the script in linux and you canunderstand this is comment :)// /*import os##include<os.h>print(50*"-")#will print - fifty timesprint("file name :%s"%(__file__))#will reveal current file nameprintf("%s",__file__)name=raw_input("What is your name :")#get i/p from userprint ("Name:"+name)#print the nameprint(50*"=") list_comp.py#! /usr/bin/env pythondef looping(): x=[] for y in range(20): if y%2 == 0: x.append(y) print xdef list_comp(): x=[y for y in range(20) if y%2 ==0 ] print xlooping()list_comp()import disdis.dis(looping)dis.dis(list_comp)
  2. 2. fav_movies.py#! /usr/bin/env python"""This file contains few ways how one can read and write content tofile in python"""count=0file="fav_movies.txt"file_="fav_movie_list.txt"movie_list=[]def write_to_file(): Writing string to file global file,count fp=open(file,w) print 50*"=" print("Enter 5 movie names you like ") while count < 5 : movie=(raw_input("Enter the fav movie:"))+"n" movie_list.append(movie) fp.write(movie) count+=1 fp.close() print 50*"="def read_a_line(): global file fp=open(file,r) fp.close() print ("n Reading one line")def readlines(): global file fp=open(file,"r") print fp.readline()#will read only one line fp.close() print "="*50def write_list(): global file_,movie_list print("Writing entire list into a file ") f=open(file_,"w") f.writelines(movie_list)#write entire list to a file f.close() print "="*50def read_using_for(): global file
  3. 3. print ("reading input using for loop") for line in open(file): print line print "="*50def one_liner(): global file print ("read entire contents in a single line") print(open(file).read())#will read all lines in one stretch print 50*=write_to_file()print ("doc for %s:%s "%(write_to_file.func_name,write_to_file.__doc__))read_a_line()readlines()write_list()read_using_for()one_liner()print ("__doc__",__doc__) get_particular_line.py#! /usr/bin/env pythonfile="text.txt"import linecachetheline=linecache.getline(file,2)print thelinezip_length.py#! /usr/bin/env pythonimport zipfilez=zipfile.ZipFile("day1.odp.zip","r")for filename in z.namelist(): print "File:",filename bytes=z.read(filename) print has,len(bytes),bytes details.py#! /usr/bin/env pythonimport socketmyname=socket.getfqdn(socket.gethostname())myaddr=socket.gethostbyname(myname)print "System name:%s"%(myname),"Ip:",myaddr
  4. 4. password_gen.pyimport string,randomchars=string.lowercase+string.uppercase+string.digitsprint .join([random.choice(chars) for i in range(0,10)])

×