Click here to Login

Python Programs for s1 CS/IT KTU


1.add two numbers

import os
os.system('clear')
#system('clear')
num1=input('first no:')
num2=input('second no:')
sm=num1+num2
print "the sum of ",num1,"and ",num2, "is" ,sm

2. Program to implement a dictionary

letters=input("Enter a string: ")
print letters
dt={}.fromkeys(letters,0)
for ch in letters:
if ch in dt:
dt[ch]=dt[ch]+1
print dt

"""
output
Enter a string: "apple"
apple
{'a': 1, 'p': 2, 'e': 1, 'l': 1}
"""
3. Fibonacci series
t1=0
t2=1
tn=0
dt={1:0,2:1}
l=input("limit:")
#print t1
#print t2
cnt=2
while cnt<l:
tn=t1+t2
#print tn
t1=t2
t2=tn
cnt =cnt+1
dt.setdefault(cnt,tn)
print dt
n=input("enter the nth value u want from fibonacci series ")
print dt[n]

"""
output
limit:7
{1: 0, 2: 1, 3: 1, 4: 2, 5: 3, 6: 5, 7: 8}
enter the nth value u want from fibonacci series 3
1

"""
4. Vowels in a String

letters="aeiou"
str=input("Enter a string:")
dt={}.fromkeys(letters,0)
for ch in str:
if ch in dt:
dt[ch]=dt[ch]+1
print dt

"""
output
Enter a string:"apple"
{'a': 1, 'i': 0, 'e': 1, 'u': 0, 'o': 0}
"""
5.Even or Odd

a=input('no:')
if a%2==0:
 print "even"
else:
 print "odd"
 print "hi"
else :
print "hello"
"""if a%2!=0:
print "odd"""

6.Factorial of a number

n=input('n:')
fact=1
for i in range(1,n+1):
fact=fact*i
print fact

7.File Operations

f=open("tst.txt",'r+')
#print (f.read())

f1=open("dest.txt",'a+')
for ln in f:
      #print(ln)      
    f1.write(ln)
f1.close()#other wise dont print to keyboard
f1=open("dest.txt",'r+')
print (f1.read())

8.Usage of Functions

def prnt(str):
print str
return
print prnt("hello")

9.Add two number using Functions

a=input("1no")
b=input("2no")
def ad():
c=a+b
return c
print ad()

10. Factorial using recursion

def refact(x):
if x==1:
return 1
else:
return(x*refact(x-1))
num=input("no:")
if num>=1:
print 'factorial is',refact(num)

11. Multiplication table 

for i in range(1,10):
for j in range(1,10):
print i,'*',j,'=',i*j
print "************"

12. Check number is palindrome or not

n=input("num:")
w=n
rev=0
#steps in loop let dem do
while(n!=0):
rem=n%10
rev=rev*10+rem
n=n/10
print rev
if rev ==w:
print "paliandrome"
else:
print "not palindrome"

13. Check wethwe prime or not

num= input("no:")
if num>1:
for i in range(2,num):
if (num%i)==0:
print "not prime"
break

else:
print "prime"


14..Display prime numbers  between two limits

lw = input("lw:")
up=input("up:")

for num in range(lw,up+1):
if num>1:
flag=0
for i in range(2,num):
if (num%i)==0:
flag=1
if flag==0:
print num

15.Diplay a pyramid

#a=10
for i in range(1,11):
for j in range(11,-i):
print " ",
for j in range(1,i):
print "*",
for i in range(i,0,-1):
print "&",
"""for s in range(a,1,-1):
print " ",
print "*",
print "\n"
a=a-1"""
print "\n"


16.Reverse a number

n=input("num:")
rev=0
#steps in loop let dem do
while(n!=0):
rem=n%10
rev=rev*10+rem
n=n/10
print rev

17. Sort a string in alphabetical order

word=input("Enter the string : ")
l=len(word)-1
for i in range(0,l):
for j in range(0,l):
if (word[i]>word[j]):
temp=word[i]
word[i]=word[j]
word[j]=temp

print word

18.Check whether String is palindrome or not

word=input("Enter the string : ")#string should enter in "" or ''
i=0
p=1
j=len(word)-1
while i<j:
if word[i]!=word[j]:
p=0
i=i+1
j=j-1
if p==1:
print "palindrome"
if p==0:
print "not palindrome"

19.Armstrong Number or not

n=input('Enter the number')
s=0
m=n
while(m>0):
r=m%10
s=s+(r**3)
m=m/10
if(s==n):
print 'Armstrong number'
else:
print 'Not Armstrong number'



'''OUTPUT
Enter the number 153
Armstrong number
'''
20.Sum of first n natural numbers

sum=0
i=1
n=input("Enter the limit:")
while i<=n:
num=input("Enter the number:")
sum=sum+num
i=i+1
print "sum is",sum



"""
OUTPUT
student@student-desktop:~/Desktop$ python natural.py
Enter the limit:7
Enter the number:1
Enter the number:2
Enter the number:3
Enter the number:4
Enter the number:5
Enter the number:6
Enter the number:7
sum is 28
"""

21.Perfect Square or not

num=input("enter the number")
i=1
while i<=num/2:
s=i**2
if s==num:
print "perfect square"
break
i+=1
else:
print "not a perfect square"

"""
OUTPUT
student@student-desktop:~/Desktop$ python perfect.py
enter the number 16
perfect square
"""


22.Sum of digits of a number

num=input("enter the number")
s=0
while(num>0):
r=num%10
s=s+r
num=num/10
print "sum of numbers",s




"""
OUTPUT
student@student-desktop:~/Desktop$ python squares.py
enter the number 14
sum of numbers 5

"""

23.Calculator

def add(x,y):
print "Sum oif two numbers is",(x+y)
def sub(x,y):
print"Difference of two numbers is",(x-y)
def multi(x,y):
print"Product of two number is",(x*y)
def div(x,y):
print"Quotient is",(x/y)
x=input("Enter the value for x")
y=input("Enter the value for y")
z=raw_input("Enter your choice +,-,*,/: ")
if z=='addition':
add(x,y)
elif z=='subtraction':
sub(x,y)
elif z=='multiplication':
multi(x,y)
else:
div(x,y)


"""
OUTPUT
student@student-OptiPlex-3020:~/Desktop$ python calculator.py
Enter the value for x4
Enter the value for y5
Enter your choice +,-,*,/: +
Sum oif two numbers is 9
"""

24. Delete all vowels in a string


stri=raw_input("Enter the string : ")
v1="aeiou"
v2="AEIOU"
str2=""
str3=""
for i in range(len(stri)):
if stri[i] not in v1:
str2+=stri[i]
for k in range(len(str2)):
if str2[k] not in v2:
str3+=str2[k]
print str3


"""
OUTPUT
student@student-desktop:~/Desktop$ python delvow.py
Enter the string : ElEpHanT
lpHnT

"""

25. Delete Duplicate numbers in a list


l1=input("Enter the list")
l2=[]
for i in l1:
if i not in l2:
l2.append(i)
print l2


"""
OUTPUT
student@student-desktop:~/Desktop$ python duplicate.py
Enter the list[1,2,3,4,5,7,3,8,2,9,1,6,8] 
[1, 2, 3, 4, 5, 7, 8, 9, 6]
"""

26. Largest amont 3 tuples

t1=input("Enter the 1st tuple: ")
t2=input("Enter the 2nd tuple: ")
t3=input("Enter the 3rd tuple: ")
if (cmp(t1,t2)==1):
if(cmp(t1,t3)==1):
print "t1 is the largest"
else:
print"t3 is the largest"
else:
if(cmp(t2,t3)==1):
print"t2 is the largest"
else:
print"t3 is the largest"


"""
OUTPUT
student@student-desktop:~/Desktop$ python largest.py
Enter the 1st tuple: (5,6,7)
Enter the 2nd tuple: (1,2,3)
Enter the 3rd tuple: (8,4,'ab')      
t3 is the largest
"""

27.  SEARCH THE ELEMENT IN A LIST

L=input("Enter the list: ")
num=input("Enter the element: ")
for i in range(len(L)):
if (L[i]==num):
print "Element is found"
break
else:
print "Element is not found"


"""
OUTPUT
student@student-OptiPlex-3020:~/Desktop$ python search.py
Enter the list: ['a','b',1,2,3,'c']
Enter the element: 'b'
Element is found
"""
28. SUM OF SERIES
**************************************************************


def series(n):
if n==0:
return 1
else:
return n*series(n-1)
i=input("enter the number")
sum=0
for n in range(1,i+1):
if n%2==0:
sum=sum-series(n)
else:
sum=sum+series(n)
print sum


"""
OUTPUT
student@student-desktop:~/Desktop$ python series.py
enter the number5
101

29.   SORT THE LIST
**************************************************************

a=input('Enter the list :')
for i in range (len(a)):
for j in range (i+1,len(a)):
if a[i]>a[j]:
t=a[i]
a[i]=a[j]
a[j]=t
else:
print a

'''
OUTPUT
Enter the list :[2,1,5,3,6,9]
[1, 2, 3, 5, 6, 9]
'''
30.SWAP TWO NUMBERS USING FUNCTION
**************************************************************

def swap(a,b):
c=a
a=b
b=c
print "After swaping","a=",a,"b=",b
a=input("Enter the value for a: ")
b=input("Enter the value for b: ")
swap(a,b)


"""
OUTPUT
student@student-desktop:~/Desktop$ python swapfunct.py
Enter the value for a: 1
Enter the value for b: 2
After swaping a= 2 b= 1
"""

31. TRAVERSAL OF A TUPLE
**************************************************************


tup1=input("Enter the tuple")
for i in range(len(tup1)):
print tup1[i].upper()


"""
OUTPUT
student@student-OptiPlex-3020:~/Desktop$ python traversal_tuple.py
Enter the tuple  ('a','d','g','e')
A
D
G
E
"""

32.  TRAVERSAL OF A LIST
**************************************************************

l=input("Enter the list")
for i in range(len(l)):
print l[i]


"""
OUTPUT
student@student-desktop:~/Desktop$ python travsel.py
Enter the list[1,34,56,7.8,"ev"]
1
34
56
7.8
ev
"""

33.TO COUNT THE NUMBER OF VOWELS
**************************************************************


str=raw_input("Enter the string : ")
v1="aeiou"
v2="AEIOU"
for i in range(len(v1)):
count=0
for j in range(len(str)):
if str[j]==v1[i]:
count+=1
print v1[i]," count is : ",count



"""
OUTPUT
student@student-desktop:~/Desktop$ python vowel.py
Enter the string : fruit
a  count is :  0
e  count is :  0
i  count is :  1
o  count is :  0
u  count is :  1
"""
34.ROOTS OF QUADRACTIC EQUATION          *      
************************************************** 


a=input("Enter the coefficient of x^2: ")
b=input("Enter the coefficient of x: ")
c=input("Enter the constant: ")
d=((b*b-4*a*c)**1/2)
if (d==0):
x1=(-b+d)/2*a
x2=(-b-d)/2*a
print"Equation has equal roots",x1,x2
elif (d>0):
x1=(-b+d)/(2*a)
x2=(-b-d)/(2*a)
print"Equation has two unequal roots",x1,x2
else:
print"Equation has no real roots"



"""
OUTPUT
student@student-OptiPlex-3020:~/Desktop$ python eqn.py
Enter the coefficient of x^2: 10
Enter the coefficient of x: 10
Enter the constant: 5
Equation has no real roots

student@student-OptiPlex-3020:~/Desktop$ python eqn.py
Enter the coefficient of x^2: 1
Enter the coefficient of x: 4
Enter the constant: 4
Equation has equal roots -2 -2

"""

35. GRADE OF A STUDENT                *      
************************************************** 
M1=input("Enter the mark OF M1: ")
M2=input("Enter the mark of M2: ")
M3=input("Enter the mark of M3: ")
T=300.00
D=M1+M2+M3
g=(D/T)*100.00
if (g>=90):
print "A grade"
elif (90<g>=80):
print "B grade"
elif (80<g>=70):
print "C grade"
elif (70<g>=60):
print "D grade"
else: 
print "fail"




"""
Output
student@student-desktop:~/Desktop$ python grade.py
Enter the mark OF M1: 95.00
Enter the mark of M2: 85.00
Enter the mark of M3: 90.00
A grade
"""

36.*        CHECK WHETHER LEAP YEAR OR NOT          *
**************************************************


y=input("Enter the the year: ")
if (y%4==0):
if (y%100==0):
if(y%400==0):
print "Leap year"
else:
print "Not a leap year"
else:
print "Leap Year"
else:
print"Not a leap year"


"""
Output
student@student-desktop:~/Desktop$ python leap.py
Enter the the year: 1900
Not a leap year
"""

37. POSITVE,NEGATIVE OR ZERO             *
**************************************************     


a=input("enter the number:")
if (a>0):
print"a is positive"
elif (a<0):
print"a is negative"
else:
print"a=zero"


"""
Output
student@student-desktop:~/Desktop$ python positive.py
enter the number:2
a is positive
"""

38. USERNAME AND PASSWORD                *
**************************************************


username=raw_input("Enter the username: ")
password=raw_input("Enter the password: ")
us="evan"
pa="ert"
if (username==us) & (password==pa):
print"Login successfully"
else:
print"Username and password are not correct"



"""
Output
student@student-desktop:~/Desktop$ python username.py
Enter the username: Fritzy
Enter the password: pn
Username and password are not correct
"""

39.DICTIONARY
**************************************************************

str=raw_input("Enter the string: ")
d={}
for i in str:
if i not in d:
d[i]=1
else:
d[i]+=1
print d

"""
OUTPUT
student@student-desktop:~/Desktop$ python dict1.py
Enter the string: tooth
{'h': 1, 't': 2, 'o': 2}
"""
40. READ AND WRITE A FILE
**************************************************************

f=open("file.txt","w")
str="hello\nhai"
f.write(str)
f=open("file.txt","r")
str1=f.read()
print str1


"""
OUTPUT
student@student-desktop:~/Desktop$ python file.py
hello
hai
"""

41. PICKLE AND UNPICKLE
**************************************************************

import pickle
f=open("file.txt","w")
l=[1,2,3,4]
pickle.dump(l,f)
l[3]=5
f.close()

import pickle
f=open("file.txt","r")
unpick=pickle.load(f)
for i in unpick:
print "i is",i
print"l is",l


"""
OUTPUT
student@student-desktop:~/Desktop$ python pic.py
i is 1
i is 2
i is 3
i is 4
l is [1, 2, 3, 5]
"""

42.FIBONACCI SEQUENCE USING RECURSION
////////////////////////////////////////////////////////////////////////'''

n=int(input("ENTER NUMBER OF TERMS\n"))
seq=""
def fib(n):
if n==1:
return 0
elif n==2:
return 1
elif n>2:
return fib(n-1)+fib(n-2)
if n<=0:
print "INVALID"
else:
  i=1
while i<=n: 
seq=seq+" "+str(fib(i))+", "
i=i+1
print seq

'''/                          OUTPUT
//////////////////////////////////////////////////////////////////////////

ENTER NUMBER OF TERMS
13
 0,  1,  1,  2,  3,  5,  8,  13,  21,  34,  55,  89,  144, 

ENTER NUMBER OF TERMS
-3
INVALID

43.                     ARMSTRONG NUMBER WITH FUNCTIONS
////////////////////////////////////////////////////////////////////////'''

def getcube(n):
sum=0
while n>0:
sum=sum+((n%10)**3)
n=n/10
else:
return sum
n=100
while n<=999:
if n==getcube(n):
print n
n=n+1
else:
n=n+1

'''/                            OUTPUT
//////////////////////////////////////////////////////////////////////////

153
370
371
407





39 comments: Leave Your Comments

  1. very helpful....
    Thanks a lot

    ReplyDelete
  2. can u pls upload armstrong number checking using functions

    ReplyDelete
  3. It is updated as per your request
    ...

    ReplyDelete
  4. Hi there I am so thrilled I found your website, its a fantastic post , Besant technology offerPython training in chennai

    ReplyDelete
  5. I simply wanted to thank you so much again. I am not sure the things
    that I might have gone through without the type of hints revealed by
    you regarding that situation.



    Selenium Training in Chennai

    ReplyDelete
  6. Hello there! This is my first comment here, so I just wanted to give a quick shout out and say I genuinely enjoy reading your articles. Can you recommend any other blogs/websites/forums that deal with the same subjects? Thanks.
    Java Training in Bangalore|

    ReplyDelete
  7. Hello. This post couldn’t be written any better! Reading this post reminds me of my previous roommate. He always kept chatting about this. I will forward this page to him. Fairly certain he will have a good read. Thank you for sharing. DevOps Training in Bangalore

    ReplyDelete
  8. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.

    Selenium training in bangalore

    ReplyDelete
  9. I have read all the articles in your blog; was really impressed after reading it. AWS Training in Chennai Besant Technologies is glad
    To inform you that; we provide practical training on all the technologies with MNC exports. We
    Assure you that through our training the students will gain all the sufficient knowledge to have a voyage in IT industry.

    ReplyDelete
  10. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.
    Besant technologies Marathahalli

    ReplyDelete
  11. Amazing post. Keep it up. Much thanks to you such an incredible sum for sharing your beneficial blog. Duplicate Payment Recovery | Daily Transaction Monitoring | Duplicate Payment Audit


    ReplyDelete
  12. Excellent post!!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.CFA Audit | Claims Audit | Fixed Assets Audit



    ReplyDelete






  13. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.

    Selenium Training in Chennai

    Selenium Training in Rajaji Nagar


    Selenium Training in Chennai

    Selenium Training in Porur

    ReplyDelete
  14. This information you provided in the blog that is really unique I love it!! Thanks for sharing such a great blog. Keep posting..
    Python training in Noida
    Python training institute in Noida
    Python course in Noida

    ReplyDelete
  15. Thanks for sharing this valuable and interesting article with smart content..keep updating. Audit Co-Sourcing
    Continuous Transaction Monitoring
    Duplicate Bill Check

    ReplyDelete





  16. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.

    Automation Anywhere Training in Chennai

    ReplyDelete
  17. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    health and safety course in chennai

    ReplyDelete
  18. Hi,
    I must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.
    German Classes in Chennai
    Java Training in Chennai
    German Language Course in Chennai
    German Courses in Chennai
    Best Java Training Institute in Chennai
    Java Training

    ReplyDelete
  19. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.
    AWS Training in Chennai
    Data Science Training in Chennai
    Python Training in Chennai

    ReplyDelete
  20. Thanks for sharing such a great blog Keep posting..
    Python Training
    Python Course

    ReplyDelete
  21. This is very great thinks. It was very comprehensive post and powerful concept. Thanks for your sharing with us. Keep it up..
    Oracle Training in Chennai | Oracle Training Institutes in Chennai

    ReplyDelete
  22. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.
    Java Training in Chennai | J2EE Training in Chennai | Advanced Java Training in Chennai | Core Java Training in Chennai | Java Training institute in Chennai

    ReplyDelete
  23. It’s really nice and meaningful. It’s really cool blog. You have really helped lots of people who visit Blog and provide them useful information. Thanks for sharing.

    Corporate training in Artificial intelligence in Ghana

    ReplyDelete
  24. Thanks for sharing this valuable information and we collected some information from this blog.


    Python Corporate training in Nigeria

    ReplyDelete
  25. Thanks for sharing, very informative. Top Programming Languages in 2020.

    ReplyDelete
  26. It's very Wonderful to visit your site...Enjoy Reading your Articles...informative Blogs About Java...Keep doing the same
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  27. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog.
    Oracle Training | Online Course | Certification in chennai | Oracle Training | Online Course | Certification in bangalore | Oracle Training | Online Course | Certification in hyderabad | Oracle Training | Online Course | Certification in pune | Oracle Training | Online Course | Certification in coimbatore

    ReplyDelete
  28. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic...
    Java Training in Chennai

    Java Training in Velachery

    Java Training in Tambaram

    Java Training in Porur

    Java Training in OMR

    Java Training in Annanagar

    ReplyDelete
  29. Trainingicon is offering Python training in Delhi NCR. We are a training institute in Delhi and Noida.We provide industrial training in programming like Python, PHP, Web designing, R Programming etc so if any body is looking to get trained into any skills, just let us know.following is the link to get enrilled into python batch
    Python Training in Delhi

    ReplyDelete
  30. Python is very famous among clients. Tech goliaths like Instagram, Google, Pinterest, IBM, Nokia, and Yahoo have been using the programming language. There will consistently be new roads to investigate once you get familiar with this programming language. It's anything but a profoundly popular ability. Organizations these days are liking to recruit master Python designers.
    We are offering following python courses.
    Python Training in Delhi
    Python Training in Noida
    Python Training in Ghaziabad
    Free Python Course

    ReplyDelete
  31. Thank You for publishing such a wonderfull details.We are also offering offering trainig please read the following detailsof our organization.
    TrainingIcon is the most expert and rumored WordPress Training Institute in Delhi. This organization has been leading WordPress preparing in Delhi for recent years. TrainingIcon has prepared various of the understudies and given arrangements into the top IT organizations. After the culmination of WordPress preparing now they are taking care of their responsibilities in the most famous IT firms.

    Picking different sources online for amazing web architecture and improvement will lead you towards that load of highlights that you consider in a viable way. With the accessibility of php preparing in delhi for reasonable bundles, it is feasible to investigate a definitive advancement guidelines in a precise design that you anticipate. Different scope of php courses are accessible for the fans on account of which outstanding web architectures could be acknowledged in a genuine style.
    PHP Training in Delhi

    ReplyDelete
  32. very nice article. keep up the good work.
    study mbbs abroad

    ReplyDelete
  33. HI thanku so much this infromation this is greatful blog
    cs executive
    freecseetvideolectures/

    ReplyDelete
  34. Think This Is Owsm Post, But If You Check This GATE IO

    ReplyDelete
  35. This post is so interactive and informative.keep update more information...
    Java Training in Tambaram
    java course in tambaram

    ReplyDelete