## Python Exercise13

#regular expressions
import re

txt=”You can call me on 9988888888. My ATM pin is 1234 . You are good”
#find all occurances of “ATM”
words=re.findall(“ATM”,txt)
print(“Occurances of ATM : “,words)

#find if the string begins with “You”
words=re.findall(“^You”,txt)
print(words)

#find if the string ends with “You”
words=re.findall(“You\$”,txt)
print(words)

#find all digits in the string”
words=re.findall(“d”,txt)
print(words)

#find one or more digits”
words=re.findall(“d+”,txt)
print(words)

#find ATM pin in the string”
words=re.findall(“dddd”,txt)
print(“ATM Pin”,words)

#find ATM pins in the string”
words=re.findall(“sdddds”,txt)
print(words)

#find ATM pins in the string”
words=re.findall(“sd{4}s”,txt)
print(words)

#find ATM pins in the string”
words=re.findall(r”bd{4}b”,txt)
print(words)

#find all ATM pin in the string and replace with ****
pin=re.sub(r”bd{4}b”,”****”,txt)
print(“Pin: “,pin)

## Python Exercise12

Write a program to take input of integers from the user and divide the numbers

handle TypeError and ZeroDivisionError in your program

try:

a=input(“Please enter the dividend : “)

b=input(“Please enter the divisor : “)

print (a/b)

except TypeError:

print( “Both values must be integer”)

except ZeroDivisionError:

print (“Divisor must not be zero”)

Write a program to enter the amount to withdraw from ATM handle your errors

counter=1

while True:

amount=input(“Enter the amount you wish to withdraw : “)

try:

print(int(amount))

break

except ValueError:

print(“Pl. check the amount you entered”)

if counter < 4:

counter+=1

else:

print(“I am fed up with you”)

break

Write a Program to take input from the users and handle errors in your program

b=True

while b:

try:

x=int(x)

y=int(y)

z=x/y

except ZeroDivisionError as err:

print( “Handling run-time error”,err)

b=False

except ValueError as ver:

print (“Both values must be integer”,ver)

b=False

else:

print (“Division of two numbers: “,z)

Write a program to handle errors and also use finally

try:

inverse = 1.0 / x

print(inverse)

except ValueError:

print( “You should have given either an int or a float”)

except ZeroDivisionError:

print (“Number cannot be divided by zero”)

finally:

print (“There may or may not have been an exception.”)

Write a program to raise your own exception

def func(level):

if level < 1:

raise Exception(“Invalid level, should be greater than 1”)

else:

print(“Level greater than 1”)

func(1)

func(0)

## Python Exercise11

Write a program to take input from command line and print all the values

from sys import argv

script,first, second =argv

print (“The script is called:”,script)

print( “The first variable is :”,first)

print (“Your Second variable is :”, second)

Write a program to get input from command line and add those values

import sys

print(len(sys.argv))

if (len(sys.argv)>3):

sum=0

for i in sys.argv[1:]:

sum=sum+int(i)

print(sum)

else:

print (“Please give atleast two parameters only”)

print( “My name=”,sys.argv)

print (“First arg”,sys.argv)

print( “Second arg”,sys.argv)

Write a program to get input from command line and print number of arguments received

import sys

print (“My name is {}”.format(sys.argv))

Write a program to find the factorial by passing  the values from the command line

import math

import sys

for x in sys.argv[1:]:

print(“{} – {}”.format(x,math.factorial(int(x))))

Program to find the factorial by passing it from the command line, if the user does not pass the values , system should prompt for the input

import math

import sys

if len(sys.argv) == 1 :

num=input(“Enter a number: “)

print(math.factorial(int(num)))

else:

for x in sys.argv[1:]:

print(“{} – {}”.format(x,math.factorial(int(x))))

## Python Exercise10

Write a program to find the random numbers from 1 to 100 and call the function for 500 times and print how many times each number has been repeated

import random

def myrandom():

return random.randint(1,100)

#2. Call the function 500 times and save the results into a list.

r=[]

for x in range(500):

r.append(myrandom())

#3. Print how many times each number has repeated

for x in set(r):

print( x,r.count(x))

Write a program to print the size of the file and the time file was created

import os,time

size=os.stat(“C:/Users/exercise.py”).st_size

ctime=os.stat(“C:/Users/exercise.py”).st_ctime

print (“Size of the file :”,size)

print (“Created :”,ctime)

print (“Current time: “,time.time())

print (“Current time – Created time :”,time.time() – ctime)

Example for datetime module

import datetime

d1 = datetime.date(2008, 3, 12)

print(‘d1:’, d1)

d2 = d1.replace(year=2015,day=4,month=10)

d3=d1.replace(day=10)

d4=d1.replace(month=10)

print(‘d2:’, d2)

print(‘d3:’,d3)

print(‘d4:’,d4)

Example of datetime module

import datetime

today = datetime.date.today()

print (‘Today :’, today)

one_day = datetime.timedelta(weeks=2)

yesterday = today – one_day

print( yesterday)

print (‘Yesterday:’, yesterday)

tomorrow = today + one_day

print( ‘Tomorrow :’, tomorrow)

print( ‘tomorrow – yesterday:’, tomorrow – yesterday)

print( ‘yesterday – tomorrow:’, yesterday – tomorrow)

Example of os module functions

import os

print(os.getcwd())                   #get working dir

os.chdir(“c:\python27”)       #change dir

print(os.getcwd())                   #get working dir

os.system(“notepad.exe”)    #run a os command from python

Write a program to compress all py files from a folder and write the files in to zip file

import os

import zipfile

import glob

myhome=”c:\users\pythonfiles”

myzip=”c:\users\pythonfiles.zip”

#go to the home directory

os.chdir(myhome)

#open an empty zip file

z=zipfile.ZipFile(myzip,’w’)

#select all the *.py files

pyfiles=glob.glob(“*.py”)

#compress and write the files into the zip file

for file in pyfiles:

print(“Zipping file {}”.format(file))

z.write(file)

#close zip file

z.close()

print(“Zipping Complete”)

## Python Exercise9

Write a program to stop the search as soon as we find 50 in the list

numbers = [100, 25, 125, 50, 150, 75, 175]

for x in numbers:

print( x )

if x == 50:

print( “Found It!” )

break

Write a program to skip all triple digit numbers

numbers = [100, 25, 125, 50, 150, 75, 175]

for x in numbers:

if x >= 100:

continue

print( x )

<

Write a program to unpack the values to variables

colors=”red,blue,green,yellow,pink”
#print(colors.split(‘,’))               # list of colors
r,b,g,y,p=colors.split(‘,’)            # unpacked in to variables
print(r,b,g,y,p)

Write a program to join each value with **using  join

colors=[“red”,”blue”,”green”,”yellow”,”pink”]
print(“**”.join(colors))

## Python Exercise8

1. Write a program to write all multiple of 7 from 10 to 100 in to a file

f=open(‘file1.txt’,’w’)

for i in range(14,100,7):

f.write(str(i)+ ‘n’)

f.close()

2.  Write all elements in the list to a file

a=[‘hellon’,’hown’,’aren’,’youn’]

f=open(‘file1.txt’,’w’)

a=[‘hellon’,’hown’,’aren’,’youn’]

f.writelines(a) #write all the elements in list into file

f.close()

print(f.closed)        #Prints whether the file is closed or not

3. Write a program to count the number of words in a text file

num_words = 0

f=open(‘input.txt’,’r’)

for line in f:

words = line.split()

num_words += len(words)

print(“Number of words:”,num_words)

f.close()

4. Write a program to count the occurrences of a word in a text file

f=open(‘input.txt’,’r’)
word=input(“Enter word to be searched:”)
k = 0
for line in f:

words = line.split()

for i in words:

if(i==word):

k=k+1

print(“Occurrences of the word:”,k)

f.close()

5. Write a program to copy the contents of one file to another file

infile=open(‘input.txt’,’r’)
outfile=open(‘out.txt’,’w’)
for line in infile:

outfile.write(line)

infile.close()
outfile.close()

6.  Write a  Program to Read a File and Capitalize the First Letter of Every Word in the File and print it on the screen

f=open(‘out.txt’,’r’)

for line in f:

l=line.title()

print(l)

7. Write a program to take each item from the list and check whether we are able to ping to the system or not

import os,time

#function that returns on or off

def isup(host):

pingstring= “ping -n 1 {}”.format(host)

status=os.system(pingstring)

if not status:

return host + ” is up”

else:

return host + ” is down”

while True:

for node in nodes:

print(isup(node))

time.sleep(1) #sleeps for a second

8. Write a program to open and write to a file if the file exists else create a new file  and write to the file

import os,sys

#Opening a file if exists else creates a new file

fd = os.open( “c:\Users\new2.txt”, os.O_RDWR|os.O_CREAT )

#Write string to the file

os.write(fd, “Writing in to test file”)

#Closing the opened file

os.close(fd)

print “Closed the file successfully”

9.  Write a program print all the files which are more than 100 bytes

import os

import glob

import time

mydir=”C:/Users/Exercises”

mysize=100

os.chdir(mydir)

myfiles=glob.glob(“*.py”)

for file in myfiles:

fsize=os.stat(file).st_size

if  fsize > mysize:

print(file,fsize)

10.  Write a program to get the files that were created in the last 4 hours

import glob,os,time

filedir=(“C:/Users/Exercises”)

os.chdir(filedir)

pyfile=glob.glob(‘*.py’)

totalsize=0

for file in pyfile:

if time.time()-os.stat(file).st_ctime < 4 *60 *60:

totalsize+=os.stat(file).st_size

print (file,os.stat(file).st_size)

print (totalsize)

11.  Write a function input_stats that accepts a file name as a parameter and that reports the longest line in the file.

example input file, input3.txt:

Smile it makes you beautiful.

Do that every morning and you’ll start to see a big difference in your life.

expected output:76

def input_stats(filename):

f = open(filename,’r’)

longest = “”

for line in f:

#print (len(longest))

if len(line) > len(longest):

longest = line

print(“Longest line =”, len(longest))

print(longest)

input_stats(“input3.txt”)

12. Create a dictionary from text file

Sample File :

car=mode of transport

bp=bloodpressure

lvl=cholestrol

stop=busstop

railways=irctc

city=mumbai

Write a program to read from file, split the line with ‘=’ and store it as words and meanings in to the dictionary

f=open(‘words.txt’,’r’)

words={}

for line in f:

pos=line.index(‘=’)             #find the index of =

word=line[:pos]                 #gets the word

#print (word)

meaning=line[pos+1:].rstrip()   #gets the meaning

words[word]=meaning             #adds the word and meaning to the dictionary

print (words)

f.close()

13. Previous program will not work if there are comments and blanklines, write a program

so that it eliminates blank lines and comments and adds the other words and meanings to the dictionary

f=open(‘words1.txt’,’r’)

words={}

for line in f:

line=line.strip()

if line and not line.startswith(‘#’):

#if ‘=’ in line:

pos=line.index(‘=’)#find the index of = #prints the word

word=line[:pos]  #

meaning=line[pos+1:].rstrip()#meaning

words[word]=meaning

print (words)

f.close()

14. Write a program to print the details of dirname, subdir and files

import os,time

for (dirname, subdir, files) in os.walk(‘c:/pythonEx’):

for myfile in files:

filename=os.path.join(dirname,myfile)

print(filename)

## Python Exercise7

1. Write a program to read file contents at a time

f = open(‘input.txt’,’r’)

f.close()

1. Write a program to read a file char by char

f = open(‘input.txt’,’r’)

f.close()

1. Write a program to read a file line by line

f = open(‘input.txt’,’r’)

f.close()

1. Write a program to read all lines in to a list

f = open(‘input.txt’,’r’)

f.close()

1. Write a program to write in to a file

f = open(‘input.txt1′,’w’)

f.write(“this is line1”)

f.close()

1. Write a program to append to an existing file

f = open(‘input.txt’,’a’)

f.write(“nthis is newline”)

f.close()

1. Write a program to print nth line and print range of lines

f=open(“input.txt”,”r”)

print(contents)                               #prints 6th line

print(contents[6:12])                         #prints from 7th to 11th

f.close()

1. Write a Program to read the file and print

Output:Item: Pens,Quantity: 10,Price: 10.10

Pens,10,10.10

Pencils,20,15.14

Erasers,30,10

Box,10,50

Bags,10,200

f=open(“prices.txt”,”r”)                                                                                       #open the file in read mode

for line in f:                                                                                                            #get a line

fields=line.rstrip().split(‘,’)                                                                             #split the line

print(“Item: {},Quantity: {},Price: {}”.format(fields,fields,fields))           #print the 3rd field

f.close()

9. Write a program to get all the .txt files from the current working directory

import glob

import os

#print( os.getcwd())

files=glob.glob(‘*.txt’)

print (len(files))

print (files)

1. Write a program to print all the lines which does not have ‘smile’

f=open(‘input3.txt’,’r’)

for line in f:

if “smile”.lower() in line.lower():continue

print(line)

## Python Exercise6

Write a function to read each char from the word if the char matches with the word find the index of that char,store it in indices return indices

def get_indices(word,char):

indicies=[]

for x in range(len(word)):

if word[x]==char:

indicies.append(x)

print(indicies)

get_indices(“apple”,”p”)

Write a function to calculate the factorial of a given number

def factorial(n):

fact=1

for i in range(2,n+1):

fact=fact*i

return fact

print(factorial(5))

Write a function to find fibonacci series

def fib(x):

a, b = 0, 1

while a < x:

print(a)

a, b = b, a+b

print( “Fibonacci series..” )

fib(50)

Program make a simple calculator that can add, subtract, multiply and divide using functions

Select operation.

2.Subtract

3.Multiply

4.Divide

Enter choice(1/2/3/4):

# This function adds two numbers

return x + y

# This function subtracts two numbers

def subtract(x, y):

return x – y

# This function multiplies two numbers

def multiply(x, y):

return x * y

# This function divides two numbers

def divide(x, y):

return x / y

print(“Select operation.”)

print(“2.Subtract”)

print(“3.Multiply”)

print(“4.Divide”)

# Take input from the user

choice = input(“Enter choice(1/2/3/4):”)

num1 = int(input(“Enter first number: “))

num2 = int(input(“Enter second number: “))

if choice == ‘1’:

elif choice == ‘2’:

print(num1,”-“,num2,”=”, subtract(num1,num2))

elif choice == ‘3’:

print(num1,”*”,num2,”=”, multiply(num1,num2))

elif choice == ‘4’:

print(num1,”/”,num2,”=”, divide(num1,num2))

else:

print(“Invalid input”)

Write a program to calculate the average of number in a given list

Note: Take input from the user,ie., Number of elements to be inserted:

and take the input for n number of times

def average(rep):

li = []

for numb in range(rep):

elem = int(input(“Enter Element : “))

li.append(elem)               #appending element to the list

average=sum(li)/rep               #Finding the average

print(“Average of the list: “,round(average,2))

average(int(input(“Enter number of elements to be inserted: “)))

Visit www.mongofactory.com to know more about the trainer.

## Python Exercise5

Print values from 0 to 10.

for i in range(11):

print(i)

Print values from 10 to 0

for x in range(10,-1,-1):

print(x)

Print values from 100 to 170

for x in range(100,171):

print(x)

Print all the even numbers from 0 to 100

for x in range(0,100,2):

print(x)

Create a list with different string values, and print all the values

cars=[“maruti”,”hyundai”,”bmw”,”benz”]

for car in cars:

print(car)

Initialize a variable with a string and print each character

city=”Bangalore”

for char in city:

print(char)

convert the below c for loop into python

for (i=65;i<=345;i=i+5)

{

printf i*i;

}

for i in range(65,346,5):

print i*i

convert the below c for loop into python

for (i=365;i>=45;i=i-5)

{

print i*i;

}

for i in range(365,44,-5):

print i*i

Write a program to take input from the user and then count the number of vowels

contained in the string.

Eg: Input: Indira Output:Number of Vowels are :3

Input: indira Output:Number of Vowels are :3

count = 0

char = input(“Enter some word:”)

vowels=[‘a’,’e’,’i’,’o’,’u’]

for x in char:

if x.lower() in vowels:

count=count + 1

print(“Number of vowels are : “,count)

Write a program to remove the duplicates from the list

s=[24,20,2,60,70,80,24,2,100,60,70]

s=[24,20,2,60,70,80,24,2,100,60,70]

newlist=[]

for x in s:

if(x not in newlist):

newlist.append(x)

print(newlist)

Write a  program to print all numbers in a range divisible by a given number

Eg: Enter lower range limit:1

Enter upper range limit:10

Enter the number to be divided by:2

2

4

6

8

10

lowerlimit=int(input(“Enter lower range limit:”))

upperlimit=int(input(“Enter upper range limit:”))

n=int(input(“Enter the number to be divided by:”))

for i in range(lowerlimit,upperlimit+1):

if(i%n==0):

print(i)

Write a program to print all integers that are not divisible by

either 2 or 3 and lie between 1 and 50

for i in range(0,51):

if(i%2!=0 and i%3!=0):

print(i)

Write a program to print an inverted star pattern

Enter number of rows: 3

***

**

*

n=int(input(“Enter number of rows: “))

for i in range (n,0,-1):

print((n-i) * ‘ ‘ + i * ‘*’)

Create a list with names in it. Print all the names whose length is >5

names=[“Ujwal”,”Shilpa”,”Sandya”,”Vishal”,”Keerthi”,”Shankari”,”Ram”]

for name in names:

if(len(name)>5):

print(name)

Visit www.mongofactory.com to know more about the trainer.

## Python Exercise4

1. Write a program to create list of squares of all odd numbers below 50 and print the list.

a=[]

for x in range(1,50,2):

a.append(x*x)

print(a)

2.Initialize a variable with number, Write a program to guess (take input from user)

the number that has been initialized in the program

if the guessed number is lower than the number : print guess higher number

if the guessed number is higher than the number : print guess lower number

if the guessed number is correct print “your guess is right”

numb = 35

guess = int(input(“Take a guess: “))

while (guess != numb):

if (guess > numb):

print(“Guess the Lower number”)

else:

print (“Guess the Higher number”)

guess = int(input(“Take a guess: “))

print(“You guessed it!  The number was”, numb)

3. Program to get the grade of 10 students in a class and find average of the class

total = 0

while gradeCounter <= 10:               # loop 10 times

average = total / 10                    # integer division

print (“Class average is”, average)

4.Write a program to print fibonacci series below 10 (0,1,1,2,3,5,8)

a, b = 0, 1

while a < 10:

print a

a, b = b, a+b

Visit www.mongofactory.com to know more about the trainer.