# Python files  demo

# This function writes data into file
def fileWrite():
# fopen=open("sample.txt","w+")
with open("sample.txt","w+") as fopen: # Trying to open a file using 'with' operator. This automatically closes the file.
msg=raw_input('\nEnter the string you want to add to file:\t')
fopen.write(msg)
# fopen.close()

# This function reads data from a file
def fileRead():
fopen=open("sample.txt","r+")
msg=fopen.read() # You can also specify the read(arg) to some numeric value to read till specific line size.
print '\nCharacters read from the file: ',msg
fopen.close()

# This function will append data to existing file
def fileAppend():
fopen=open("sample.txt","a+")
msg=raw_input('\n Enter the string you want to append: ')
fopen.write(msg)
# Reading characters from file after appending
str=fopen.read()
print str

# This function splits words in a file & also counts # of words
def fileSplit():
with open("sample.txt","r+") as fobj:
data=fobj.read()
count=0
for i in data:
word=data.split()
print word
print 'Word count is:',data.count(' ')+1 # This function counts number of words in file

print '\n *** This program demonstrates various operations on Files****'
print '\n 1. Write to a file \n 2. Read from file \n 3. Append data to file \n 4. Word count in file'
option=input('Enter the option you want to perform:')

if option==1:
print '***Write() will append the data to mentioned file (or) will create a new file ***'
fileWrite()

elif option==2:
print '\n *** Read() function will try to read data from existing file***'
fileRead()

elif option==3:
print '\n *** APpend() function will append data to mentioned file (or) create a new file if file doesn\'t exist'
fileAppend()

elif option==4:
print '\n ****Counting Number of words in file ****'
fileSplit()

else:
print 'Your option was not right'

# Output:



#*****geometricClass.py*****

# Python Geometric class

class geometryClass:
def __init__(self,length,breath,radius,height,base1,base2):
self.length=length
self.breath=breath
self.radius=radius
self.height=height
self.base1=base1
self.base2=base2
def square(self):
area_sqr=self.length ** 2
return area_sqr;
def rectangle(self):
area_rect=self.length*self.breath
return area_rect;
def circle(self):
area_circle=3.14*(self.radius ** 2)
return area_circle;
def triangle(self):
area_tri=0.5*self.base1*self.height
return area_tri;
def parallelogram(self):
area_para=self.base2*self.height
return area_para;
def trapezoid(self):
area_trap=0.5*self.base1*self.base2*self.height;
return area_trap;

shape=geometryClass(5,3,2,4,6,3);
print shape.square();

# *****Shape.py******
# this page imports the Shape class and implements those functions

from geometryClass import *

print '\n *** Area of various Geometric shapes***'
print ' 1. Square \n 2. Rectangle \n 3. Circle \n 4. Triangle \n 5. Parallelogram \n 6. Trapezoid'
option=input('\n Select the geometric shape to find the area:')

if option==1:
length=input('Enter the length of square side:')
area_sqr=geometryClass(length,0,0,0,0,0);
print ('Area of square:',area_sqr.square());
elif option==2:
length=input('Enter the length of rect: ')
breath=input('Enter the breadth of rect: ')
area_rect=geometryClass(length,breath,0,0,0,0)
print ('Area of Rectangle:',area_rect.rectangle());
elif option==3:
radius=input('Enter the radius of circle: ')
area_circle=geometryClass(0,0,radius,0,0,0)
print ('Area of Circle:',area_circle.circle());
elif option==4:
base=input('Enter the base of triangle: ')
height=input('Enter the height of triangle: ')
area_tri=geometryClass(0,0,0,height,base,0)
print ('Area of Triangle:',area_tri.triangle());
elif option==5:
base=input('Enter the base of parallelogram: ')
height=input('Enter the height of parallelogram: ')
area_par=geometryClass(0,0,0,height,0,base)
print (' Area of parallelogram: ',area_par.parallelogram());
elif option==6:
base1=input('Enter the base1 of trapezoid: ')
base2=input('Enter the base2 of trapezoid: ')
height=input('Enter the height of trapezoid: ')
area_par=geometryClass(0,0,0,height,base1,base2)
print (' Area of trapezoid: ',area_par.trapezoid());
else:
print 'No Geometric shape existing with this selection. please try back.'

Output:

# Python Function demo

print '*** Select the operation you would like to perform *****'
print '\n 1. Prime Number between given interval \n 2. Armstrong Number \n 3. Even or Odd \n 4. Factorial Of number \n'
option=input('Option:')
message='********* Welcome to python programming *****'
def test(message):
print message
return;
test(message);

def prime_number(prime_range):
for num in range(2,prime_range+1):
for i in range(2, num):
if (num%i==0):
break
else:
print num
return;

def armstrongNumber(num):
temp=num;
sum=0;
while temp >1:
rem=temp%10;
sum+=rem**3
temp
if sum==num:
print (num,'is an Armstrong Number')
else:
print (num,'is not an Armstrong Number')
return;

def evenodd(num):
if(num%2==0):
print (num,'is Even Number')
else:
print (num,'is Odd Number')
return;

def factorial(num):
fact=1
if(num < 1):
print '\n Factorial doesnt exist for negative numbers'
elif num==0:
print '\n Factorial of 0 is 1'
else:
for i in range(1, num+1):
fact=fact*i;
print ('\n Factorial of ',num,' is: ',fact)
return;

if option==1:
prime_range=input('\n Enter the range till you want to find prime numbers:')
prime_number(prime_range);

elif option==2:
num=input('\n Enter the number to check if it is armstrong or not: ')
armstrongNumber(num);

elif option==3:
num=input('\n Enter the number to find even or odd: ')
evenodd(num);

elif option==4:
num=input('\n Enter the number to find factorial: ')
factorial(num);
else:
print '\n Invalid option'

# Python dictionary basics operations

data={'Name':'Viv','id':'yom439','Major':'CS','Degree':'MS'}

print (data['Name'])
print (data['Major'])

print ('\n Before adding new key to dictionary');
print("\n",data)

data['Sem']=3 # Adding new key to dictionary

print ('\n After adding new key to dictionary');
print("\n",data)

#Notes: data.clear() clears all entries in dictionary
#Notes: del data; deletes dictionary

# Converting lists into Dictionaries
print '\n Converting lists into Dictionaries'

states={}
numofstates=int(raw_input('\n Enter number of states'))
for i in range(0, numofstates):
statename=raw_input('\n Enter the state:')
states[statename]={}

capitals={}
for j in range(0,numofstates):
capitalname=raw_input('\n Enter the capital name:')
capitals[capitalname]={}

# Step 1: Convert the lists which you want to make dictionary into tuple format using zip()

state_capital=zip(states,capitals)
print '\n'
print(state_capital)

# Step 2: Now convert this tuple into dictionary using dict()

states_and_capitals=dict(state_capital)
print '\n'
print(states_and_capitals)

# This program holds basic operations performed by list such as 'Adding new entry', 'Inserting list element', 'Extending list'

# List operations
stud_names=[]
stud_id=[]
cousins=['Vivek','Veerain','Priyanka','Shirisha','Shravya']
friends=['Abhi','pri','Sammmmmy','Sai','Shaaaa','hemu','adii','sowji','murali','venky','Sanndy']

names=[]

print '***** What action you would like to do ***** \n'
print '1. Add New Student name & id\n'
print '2. Insert student details \n'
print '3. Extend lists \n'

operation=input('Enter the operation you would like to perform: ')

if operation==1:

# Use of 'append' keyword

sname=raw_input('Enter the student name: ')
stud_names.append(sname)
cousins.append(sname)
sid=input('Enter student id: ')
stud_id.append(sid)
print('Students:',stud_names)
print('Student Id:',stud_id)

elif operation==2:

# Use of 'insert' keyword

sindex=input('Enter the index position you want to insert the name: ')
sname=raw_input('Enter the student name: ')
stud_names.insert(sindex,sname);
cousins.insert(sindex,sname) # This is just another example
print(cousins)

elif operation==3:
print '**************** Full list of cousins and friends would be ************** \n'

# Use of 'extend' keyword

names.extend(cousins)
names.extend(friends)
print(names)
print('\n sorted names list: ',names.sort())
print('\n Length of names list is :',len(names)) # Use of 'len' function
search=raw_input('Enter the name you would like to Search: ')

# Use of 'in'& 'not in' keyword

if search in names:
print 'Search Successful'
elif search not in names:
print 'Search unsuccessful'
else:
print 'Invalid operation'


# Programming illustrating how we can use 'list' with iterations using for loop


num1=int(raw_input("Enter first number"));
num2=int(raw_input("Enter second number"));
num3=int(raw_input("Enter third number"));
num4=int(raw_input("Enter fourth number"));
num5=int(raw_input("Enter fifth number"));
num6=int(raw_input("Enter sixth number"));

number=[num1, num2, num3, num4, num5, num6]; #this list(number) holds values provided by users and form an input to for loop.

# these empty lists will hold even and odd number provided by user in their lists
even_num=[]
odd_num=[]

print ("The provided numbers are:",number);

for value in number:
if value%2==0:
even_num.append(value);
elif value%2!=0:
odd_num.append(value);
else:
print("Value is neither even nor odd");

print('\n List of Even numbers are:',even_num);

print('\n List of odd number are:',odd_num);

# A python program that uses 'Conditional statements / Decision Making' and operates on user specified input


num1=input("enter first number:"); # This will read the input and tries to understand.
num2=int(raw_input("enter second number:")); #raw_input() will convert the provided input to string by default. Ex: try removing typecasting int() and run and provide the operation 1 or 6 and see the difference.


print("*****Possible Arithmetic operations*****\n");
print("1. Addition");
print("2. Subtraction");
print("3. Multiplication");
print("4. Division");
print("5. Modulo");
print("6. Exponent");

operation=input("******Enter the Arithmetic operation you would like to perform******* \n");

if operation==1:
addRes=num1+num2;
print("Addition of {0} and {1} is {2} \n".format(num1,num2,addRes));
elif operation==2:
subRes=num1-num2;
print("Subtraction of {0} and {1} is {2} \n".format(num1,num2,subRes));
elif operation==3:
mulRes=num1*num2;
print("Multiplication of {0} and {1} is {2}\n".format(num1,num2,mulRes));
elif operation==4:
divRes=float(num1)/float(num2);
print("Division of {0} and {1} is {2}\n".format(num1,num2,divRes));
elif operation==5:
modRes=float(num1)/float(num2);
print("Modulous of {0} and {1} is {2}\n".format(num1,num2,modRes));
elif operation==6:
expRes=num1**num2;
print("Exponent of {0} and {1} is {2}\n".format(num1,num2,expRes));
else:
 print("No such option available");


Newer Posts Older Posts Home