Wednesday, 6 November 2019

Python Programs 1


Q1. Program to find Greatest between two Numbers
a = int(input(“Enter 1st Number”))
b = (int(input(‘Enter 2nd Number’)))
if a>b :
        print (“%d is greater than %d ” % (a,b))
else :
        print (“%d is greater than %d ” % (b,a))
Q2. Program to check whether the given Year is  Leap Year.
year=int(input(“Enter Year”))
year=int(input(“Enter Year”))
if year%100 ==0 and year % 4==0 :
        print(“%d year is leap Year” %(year))
else :
         print(“%d year is not a leap Year” %(year))
Q3. Program to Calculate Grade 
s1 = int(input(“ENter Marks of 1st Subject”))
s2 = (int(input(‘ENter Marks of 2nd Subject’)))
s3 = (int(input(‘ENter Marks of 3rd Subject’)))
s4 = (int(input(‘ENter Marks of 4th Subject’)))
s5 = (int(input(‘ENter Marks of 5th Subject’)))
total =s1 +s2 +s3 +s4 +s5
per =total/5
print (“\n\n Grade = “,end=”)
if per>=90 :
      print(“A”)
elif per> 60 :
    print (“B”)
elif per> 45 :
    print (“C”)
elif per> 33 :
    print (“D”)
else :
    print (“E”)
Q4. Program to find greatest among Three Numbers
a = int(input(“ENter 1st Number”))
b = (int(input(‘ENter 2nd Number’)))
c = int(input(“ENter 3rd Number”))
if a>b :
    if a>c:
            print (“%d is greatest ” % (a))
   else :
            print (“%d is greatest” % (c))
   else :
       if b>c :
             print (“%d is greatest” % (b))
      else :
              print (“%d is greatest” % (c))
Q5. Program to check whether the no. is Even or Odd.
a=int(input(‘Enter a Number’)
if (a%2==0):
print(a, “is an Even Number”)
else: 
     print(a, “is an Odd Number”)
1. Program to print Even  Numbers up to N
N=int(input(“enter number “))
for i in range(2,N,2):
print(i,end=” “)
Q2. Program to print Fibonacci Series 0,1,1,2,3,5,8,13…….
no1=1
no2=2
print(” ,+ no1)
print(‘\n’,+no2)
x=1
while(x<=10):
no3=no1+no2
no1=no2
no2=no3
no2=no3
print (‘\n’,+no3)
x=x+1
Q3 Program to print First 10 Natural Numbers
print (‘First 10 Natural Numbers are ‘)
for i in range(1,11) :
print (i)
Q4, Program to print Multiplication Table of a Given Numbers
a=int(input(‘Enter a Number’))
i=1
while i<=10:
t=a*i
print (“%d X %d = %d ” % (a,i,t))
i=i+1
Q5 Program to check whether the given no. is Prime or not (Method I)
no=int(input(“Enter Number : “))
for i in range(2,no):
      ans=no%i
      if ans==0:
           print (‘Non Prime’)
           break
     elif i==no-1:
            print(‘Prime Number’)
(II Method)
n=int(input(“enter
n=int(input(“enter the no “))
f=0
if n==1 or n==0 :
print(“No is not complex nor composite”)
elif n>=2 :
for i in range(2, (n+1)/2):
if n%i==0 :
f=1
break
if f==0 :
print(“It is Prime Number”)
else :
print(“it is not a Prime Number”)
Q6. Program to Calculate Factorial of a given Number
a=int(input(‘Enter a Number to calculate factorial’))
f=1
while (a> 1):
    f=f*a
    a=a – 1
print (‘FActorial is %d’%(f))
Q7. Program to print First 10 Natural Numbers in reverse Order.
print (‘First 10 Natural Numbers are ‘)
for i in range(10,0,-1) :
     print (i)
Q8. Write a Program to find smallest among given numbers
sm=int(input(‘Enter :’))
for i in range ( 1,10):
      n=int(input(‘Enter :’))
      if n<sm:
          sm=n
print (“Smallest number is %d” % (sm))
Q9 Program to check whether the given number is an Armstrong Number
no=int(input(“Enter any number to check : “))
no1 = no
sum = 0
while(no>0):
     ans = no % 10;
sum = sum + (ans * ans * ans)
     no = int (no / 10)
 if sum == no1:
      print(“Armstrong Number”)
else:
       print(“Not an Armstrong Number”)
Q10 Prpgram to print series of Prime Numbers between 1 to 100
for i in range(1,101):
       for j in range(2, i):
            ans = i % j
            if ans==0:
                print (i,end=’ ‘)
                 break
11. Program to print Odd  Numbers up to N
N=int(input(“enter number “))
for i in range(1,N,2):
print(i,end=” “)
12.PROGRAM TO PRINT SERIES 1 4 7 10 13…….N
n=int(input(“enter the number “))
for i in range(1, n+1, 3):
print(i,end=” “)
13.PROGRAM TO CALCULATE X TO THE POWER Y
x=int(input(“enter the no “))
y=int(input(“enter the no “))
p=1
for i in range(1, y+1):
p*=x
print(p)
14 PROGRAM TO CALULATE LCM AND GCD
n1=int(input(“enter the no “))
n2=int(input(“enter the no “))
gcd=lcm=r=n=d=0
if n1>n2 :
n=n1
d=n2
else :
n=n2
d=n1
r=n%d
while r!=0 :
n=d
d=r
r=n%d
gcd=d
lcm=n1*n2/gcd
print((“GCD of %d and %d=%d\n”)%(n1,n2,gcd))
print((“LCM of %d and %d=%d\n”)%(n1,n2,lcm))

1. write a program to read text and count total no. of lower case letters upper Case letters, digits,alphabets, special characters, Total Words .

text=input(“Enter Text”)
l=u=d=a=s=sp=0
for ch in text:
if ch.isalpha():
a+=1
if ch.islower():
l+=1
elif ch.isupper():
u+=1
elif ch.isdigit():
d+=1
elif ch.isspace():
sp+=1
else:
s+=1
print(‘Total Alphabets are :’,a)
print(‘Total Upper Case are :’,u)
print(‘Total Lower Case are :’,l)
print(‘Total Digits are :’,d)
print(‘Total Special Characters :’,s)
print(‘Total WORDS ARE :’,sp+1)

2. write a program to read text and capitalize first letter of each word

text=input(“Enter Text”)
L=[]
NW=””
L=text.split()
for ch in L:
NW+=ch.capitalize()+’ ‘
print(NW)

3. write a program to find sub string in a text given

text=input(“Enter Text”)
sub=input(“Enter sub string to find in Text”)
f=text.find(sub)
if f==-1:
print(sub,’ is not present ‘)
else:
print(sub,’ is present at ‘,f,’ position’)

4. write a program to check whether the given string is palindrome

str=input(“Enter Text”)
rev=str[::-1]
if str==rev:
print(str, ‘ is Palindrome’)
else:
print(str, ‘ is not Palindrome’)
Q1 Write a Python program to get the smallest number from a list
Items=list(input(“Enter List Elements “))
min = list[ 0 ]
for a in list:
     if a < min:
         min = a

print(“Minimum NO. IN LIST “,max)
Q2 Write a Python program to sum all the items in a list.
Items=list(input(“Enter ListElements “))
    sum_numbers = 0
    for x in items:
        sum_numbers += x
print(sum_list([1,2,-8]))
Q3 Write a Python program to get the largest number from a list.
Items=list(input(“Enter List Elements “))
max = list[ 0 ]
for a in list:
    if a > max:
        max = a
print(“MAXIMUM NO. IN LIST “,max)
Q4. Write a Python program to remove duplicates from a list
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
    if x not in dup_items:
        uniq_items.append(x)
        dup_items.add(x)
print(dup_items)
Q5.Write a Python program to check a list is empty or not
l = []
if not l:
     print(“List is empty”)
Q6.
“”” Program to count numbers in a List”””
x = [4, 7, 9, 12, 10]
count = 0 for i in x:
count= count + 1
print(“Total number of elements = “, count)

7.

“”” Program to find average of numbers in a List”””
A = [6, 2, 7, 9, 1, 3]
Sum = 0
Avg = 0
for x in range(len(A)): Sum += A[x];
Avg = Sum/len(A); print(“Average = “, Avg)

8.

“” Program to find maximum among N numbers in a List”””
x = []
N = eval(input(“entersize of list : “)) for i in range(0, N):
x.append(eval(input(“enter”+ str(i) + ” element : “))) print(“Numbers in the list are “)
print(x)
max = x[0]
for i in range(1, N):
if ( x[i] > max): max = x[i]
print(“Maximum value in the list = “, max)

9.

“” Program to find minimum among N numbers in a List”””
x = []
N = eval(input(“entersize of list : “)) for i in range(N):
·         append(eval(input(“enter”+ str(i) + ” element : “))) print(“Numbers in the list are “)
print(x)
min = x[0]
for i in range(1, N):
if ( x[i] < min): min = x[i]
print(“Minimum value in the list = “, min)

10.

“”” Program to search a number in the list (Linear Search) “””
A=[]
N=eval(input(“entertotal numbers to be entered”)) for i in range(0,N):
A.append(eval(input(“Enter”+str(i)+”Element”)))
s=eval(input(“enterelement to be searched”)) found=-1
for i in range(0,N):
if (s==A[i]):
found=i
if (found!=-1):
print(“element found at position”,found) else:
print(“element not found”)

11.

“”” Program to arrange numbers in ascending order using Bubble Sort Method”””
x = []
N = eval(input(“entersize of list : “)) for i in range(0, N):
x.append(eval(input(“enter”+ str(i) + ” element : “))) print(x)
count = 0
for i in range(0, N-1):
for j in range(0, N-i-1): if x[j] > x[j+1]:
t = x[j]
x[j] = x[j+1] x[j+1] = t
count = count + 1 print(“Pass”,i+1,”:”, x)
print(“Total number of operations = “, count)
print(“Elements in ascending order are : \n”, x)

12. “”” Program to arrange numbers in ascending order using Insertion Sort Method”””

x = []
N = eval(input(“entersize of list : “)) for i in range(0, N):
x.append(eval(input(“enter”+ str(i) + ” element : “))) print(“List with original elements :\n”,x)
#we assume that smallest element at first index i.e. 0
for i in range(2, N): t = x[i]
k = i-1
while t < x[k]: x[k+1] = x[k] k = k – 1
x[k+1] = t
print(“Sorted List in ascending order :\n”,x)

13.

“”” Program to arrange numbers in ascending order using Selection Sort Method”””
x = []
N = eval(input(“entersize of list : “)) for i in range(0, N):
x.append(eval(input(“enter”+ str(i) + ” element : “))) print(x)
count = 0
for i in range(0, N-1):
for j in range(i+1, N): if x[i] > x[j]:
t = x[i] x[i] = x[j] x[j] = t
count = count + 1 print(“Pass”,i+1,”:”, x)
print(“Total number of operations = “, count)
print(“Elements in ascending order are : \n”, x)

14. Program to read a list and print only those numbrs which are divisible by 5 and not by 7

num=list(eval((input(“Enter numbers “))))
for i in num:
if (i%5==0 and i%7 !=0):
print (i,”is divisable by 5 but not by 7″)
15. Program to read String and check whether it is palindrome using list
msg=input(“Enter any string : “)
newlist=[]
newlist[:0]=msg
l=len(newlist)
last=l-1
for i in range(0,l):
if newlist[i]!=newlist[last]:
print (“Given String is not a palindrome”)
break
if i>=last:
print (“Given String is a palindrome”)
break
l=l-1
last = last- 1

Programs Using Pandas

Q Write a program to create dataframe for 3 student including name and roll numbers. and add new columns for 5 subjects and 1 column to calculate percentage. It should include random numbers in marks of all subjects
import pandas as pd, numpy as np, random
D={‘Roll’:[1,2,3],’Name’:[‘Sangeeta’,’Shanti’,’Swati’]}
P=[]
C=[]
M=[]
E=[]
H=[]
SD=pd.DataFrame(D)
for i in range(3):
P.append(random.randint(1,101))
C.append(random.randint(1,101))
M.append(random.randint(1,101))
E.append(random.randint(1,101))
H.append(random.randint(1,101))
SD[‘Phy’]=P
SD[‘Chem’]=C
SD[‘Maths’]=M
SD[‘Eng’]=E
SD[‘Hin’]=H
SD[‘Total’]=SD.Phy+SD.Chem+SD.Maths+SD.Eng+SD.Hin
SD[‘Per’]=SD.Total/5
Print(SD)

File Handling

1 Program to Generate Factorial from 1 to 10 and write it into file fact_till_10

file=open(‘fact_till_10.txt’,’w’)
for i in range(0,11):
f=1
for j in range (i,0,-1):
f=f*j
file.write(‘\n factorial of ‘ + str(i) +’ is ‘ + str(f))
file.close()
2. Program to find the word “This” in the myfile.py 
and display line no. in which the given word is found
f=open(“myfile.py”,”r”)
word=”This”
c=0
for i in f.readlines():
c+=1
if word in i.split():
print(“found at ” +str(c))
f.close()

3. Program to Copy an existing file to a new file

f1=open(“myfile.py”,”r”)
f2=open(“myNwfile.py”,”w”)
x=f1.read()
f2.write(x)
f1.close()
f2.close()

4. Program to count Total no. of lines present in the given file

FileName=input(‘Enter Name of File’)
File=open(FileName)
print(‘Total Number of lines in’,FileName,’are’,str(len(File.readlines())))

5. Program to read a list and print only those numbrs in file which are divisible by 5 and not by 7

f=open(“MyNum.py”,”w”)
num=list(eval((input(“Enter numbers “))))
for i in num:
if (i%5==0 and i%7 !=0):
f.write(str(i) + ” is divisable by 5 but not by 7\n”)
f.close()
___________________________________________________







No comments:

Post a Comment