Python Programs
Python Programs
Python Programs
>>>Print(“Hello world”)
>>>x=10
if x==10:
print(“ X is 10”)
Note: Execute the above line it raises indentation error. Correct the above statements as
>>>x=10
If x==0:
Print(“x is 10”)
Exercise 2
1. Write a program that takes 2 numbers as command line arguments and print its sum
Import sys
X=int(sys.argv[1])
Y=int(sys.argv[2])
Sum=x+y
Print(“sum is:”, sum)
Output:
Execution: filename.py 10 20
Sum is : 30
2. implement python script to show the usage of various operators available in python
language
a) Arithmetic operators
a,b=30,20
print(‘a=’,a)
print(‘b=’,b)
print(‘\na+b=’,a+b)
print(‘\na-b=’,a-b)
print(‘\na*b=’,a*b)
print(‘\na/b=’,a/b)
print(‘\na%b=’,a%b)
print(‘\na**b=’,a**b)
print(‘\na//b=’,a//b)
output:
a=30
b=20
a+b=50
a-b=10
a*b=600
a/b=1.05
a%b=10
a**b=large value
a//b=1
b) conditional operators
a,b=30,18
print('a=',a)
print('b=',b)
print('\na>b is ',a>b)
print('a<b is',a<b)
print('a==b is ',a==b)
print('a!=b is',a!=b)
print('a<=b is',a<=b)
print('a>=b is',a>=b)
output:
a= 30
b= 18
a>b is True
a<b is False
a==b is False
a!=b is True
a<=b is False
c) Assignment operators
a,b=30,18
print('a=',a)
print('b=',b)
c=a+b
print('c=a+b=',c)
c+=a
print('c=c+a=',c)
c-=a
print('c=c-a=',c)
c*=a
print('c=c*a=',c)
c/=a
print('c=c/a=',c)
c%=a
print('c=c%a=',c)
c**=a
print('c=c^a=',c)
c//=a
print('c=c//a',c)
Output:
a= 30
b= 18
c=a+b= 48
c=c+a= 78
c=c-a= 48
c=c*a= 1440
c=c/a= 48.0
c=c%a= 18.0
c=c^a= 4.551715960790334e+37
c=c//a 1.517238653596778e+36
3) Implement python script to read person’s age from keyboard and display whether he is
eligible for voting or not
4) implement python script to check the given year is leap year or not
Year = int(input("Enter the number: "))
if((Year % 400 == 0) or (Year % 100 != 0) and (Year % 4 == 0)):
print("Given Year is a leap Year");
# Else it is not a leap year
else:
print ("Given Year is not a leap Year")
output:
Exercise 3
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(" is Even number"(num))
else:
print(" is Odd number"(num))
output:
Enter a number: 18
Is Even number
2. Using a for loop, write a program that prints that decimal equivalents of 1/2, 1/3, 1/4,…
1/10
for i in range(1,10):
print((1/i)
output:
output:
5.Write a program using a while loop that asks the user for a number, and prints a countdown
from that number to zero.
output:
6. Develop a program that will read a list of student marks in the range 0…50 and tell you how
many students scored in each range of 10. How many scored 0-9, how many 10-19, 20-29, …
and so on.
Input: enter list of marks: 1 1 42 33 42 13 3 43
Output:
No of students Between 1-10:1
No of students Between 11-20:2
No of students Between 21-30:0
No of students Between 31-40:1
No of students Between 41-50:1
marks=[ ]
count1to10=0
count11to20=0
count21to30=0
count31to40=0
count41to50=0
n=int(input(“enter the list size”))
print(“\n”)
print(“enter list of marks ranging from 0 to 50:”)
for i in range(0,n)
item=int(input())
marks.append(item)
if item>=0 and item<=10:
count1to10++
else if item>=11 and item<=20:
count11to20++
else if item>=21 and item<=30:
count21to30++
else if item>=31 and item<=40:
count31to40++
else if item>41 and item<=50
count41to50++
print(“\n No of students Between 0-10:”)
print(“\n No of students Between 11-20:”)
print(“\n No of students Between 21-30:”)
print(“\n No of students Between 31-40:”)
print(“\n No of students Between 41-50:”)
output:
output:
12345
num=int(input("Enter a number:"))
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The number is palindrome!")
else:
print("Not a palindrome!")
Output:
Enter a number:121
The number is palindrome!
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
Enter a number: 3
The factorial of 3 is 6
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
Output:
Enter a number:5
The sum is 15
n=int(input("Enter the number till you want to print prime numbers: "))
primes = []
for i in range (2, n+1):
for j in range(2, i):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
output:
Exercise 5:
1.Define a function max_of_three() that takes three numbers as arguments and returns the
largest of them.
Output:
14
2. Write a program which makes used of function to display all such numbers which are
divisible by 7 but are not a multiple of 5, between 1000 and 2000
def findnumbers( ):
for x in range(1000 , 2000):
if x % 7 == 0 and x % 5 != 0 : #This satisfies the given requirements
print(x)
return()
print(“numbers divisible by 7 and not multiple of 5 between 1000 and 2000 are:”)
findnumbers()
output:
1001 1008 1022 1029 1036 1043 1057 1064 1071 1078 1092 1099 1106 1113 1127
1134 1141 1148 1162 1169 1176 1183 1197 1204 1211 1218 1232 1239 1246 1253
1267 1274 1281 1288 1302 1309 1316 1323 1337 1344 1351 1358 1372 1379 1386
1393 1407 1414 1421 1428 1442 1449 1456 1463 1477 1484 1491 1498 1512 1519
1526……..
def argtype(a,b,c=2):
print("a*b*c=")
print(a*b*c)
def arbitraryarg(*num):
print(num)
print("default and key argument demo")
argtype(b=2,a=2)
print("arbitrary arguments")
arbitraryarg(2,3)
output:
default and key argument demo
a*b*c=
8
arbitrary arguments
(2, 3)
def sum(n):
if n > 0:
return n + sum(n-1)
return 0
result = sum(100)
print(result)
output:
5050
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
output:
def Armstrong(n,o):
sum = 0
temp = n
while temp > 0:
digit = temp % 10
sum += digit ** o
temp = temp//10
if n == sum:
print(n,"is an Armstrong number")
else:
print(n,"is not an Armstrong number")
Output:
Enter Number:153
153 is an Armstrong number
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
output:
Enter a number:5
The factorial of 5 is 120
def find_gcd(a,b):
gcd = 1
for i in range(1,a+1):
if a%i==0 and b%i==0:
gcd = i
return gcd
# Calculating LCM
lcm = first * second / find_gcd(first, second)
print('LCM of %d and %d is %d' %(first, second, lcm))
output:
Enter first number: 6
Enter second number:8
HCF or GCD of 6 and 8 is 2
LCM of 6 and 8 is 24
Exercise 6:
L = [4, 5, 1, 2, 9, 7, 10, 8]
output:
sum=46
average=5.75
def Reversing(lst):
lst.reverse()
return lst
output:
list [10, 11, 12, 13, 14, 15]
reversed list [15, 14, 13, 12, 11, 10]
output:
list: [20, 30, 10, 45]
minimum element of the list 10
maximum element of the list 45
4. write a function reverse to reverse a list. Implement without using reverse function.
def reverse_fun(data_list):
length = len(data_list)
s = length
new_list = [None] * length
list1 = [1, 2, 3, 4, 5]
print(reverse_fun(list1))
output:
[5,4,3,2,1]
5. python program to put even and odd elements in a list into two different lists.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
output:
Enter number of elements:5
Enter element:2
Enter element:3
Enter element:5
Enter element:6
Enter element:7
The even list [2, 6]
The odd list [3, 5, 7]
myTuple = 1, 2, 3, 4
t1=1,2,3
t2=4,5,6
print (myTuple);
print("indexing operation usage, 2nd element of the tuple:", myTuple[1])
print("backward indexing operation usage, last element of the tuple:mytuple[-1]", myTuple[-1])
myTuple=myTuple+(5,)
print("adding an element to the tuple", myTuple)
print("slicing in tuple, printing 2 to 4th elments", myTuple[1:3])
print("using multiplication on tuples", myTuple*2)
print("adding to tuples t1+t2",t1+t2)
print("using in key word: element 4 is in myTuple or not", 4 in myTuple)
print("length of the tuple", len(myTuple))
print("usage of count method:", myTuple.count(3))
print("usage of index method:",myTuple.index(4) )
print("minimum element of the tuple", min(myTuple))
print("maximum elment of the tuple", max(myTuple))
output:
(1, 2, 3, 4)
indexing operation usage, 2nd element of the tuple: 2
backward indexing operation usage, last element of the tuple:mytuple[-1] 4
adding an element to the tuple (1, 2, 3, 4, 5)
slicing in tuple, printing 2 to 4th elments (2, 3)
using multiplication on tuples (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
adding to tuples t1+t2 (1, 2, 3, 4, 5, 6)
using in key word: element 4 is in myTuple or not True
length of the tuple 5
usage of count method: 1
usage of index method: 3
minimum element of the tuple 1
maximum elment of the tuple 5
7. Python program to count the number of vowels present in a string using sets
def vowel_count(str):
# Driver code
str=input("enter a string")
# Function Call
vowel_count(str)
output:
enter a stringabcdef
No. of vowels:2
#reading to stirngs
str1= input("Enter Your first string: ")
str2=input("Enter Your second string: ")
#convert the strings into sets and find intersection of two sets using & operator, then store in
#common letters in a list. Print the list
s=list(set(str1)&set(str2))
print("The common letters are:")
for i in s:
print(i)
output:
9. Python program to display which letters are in the first string but not in the second
#reading to stirngs
str1= input("Enter Your first string: ")
str2=input("Enter Your second string: ")
#convert the strings into sets and find subtraction of two sets using - operator, then store in
#common letters in a list. Print the list
s=list(set(str1)-set(str2))
print("The letters that are in first string but not in second:")
for i in s:
print(i)
output:
Enter Your first string: abcde
Enter Your second string: abdf
The letters that are in first string but not in second:
c
e
myDict = {}
output:
Please enter the Key: k1
Please enter the Value:10
Updated Dctionary={‘k1’:’10’}
myDict = {}
output:
Please enter the Key: k1
Please enter the Value:10
Updated Dctionary={‘k1’:’10’}
my_dict_1 = {'J':12,'W':22}
my_dict_2 = {'M':67}
print("The first dictionary is :")
print(my_dict_1)
print("The second dictionary is :")
print(my_dict_2)
my_dict_1.update(my_dict_2)
print("The concatenated dictionary is :")
print(my_dict_1)
output:
The first dictionary is :
{'J': 12, 'W': 22}
The second dictionary is :
{'M': 67}
The concatenated dictionary is :
{'J': 12, 'W': 22, 'M': 67}
output:
The given dictionary : {'Mon': 3, 'Tue': 5, 'Wed': 6, 'Thu': 9}
Wed is Present.
Excersice-7:
1.Implement a Python script to perform various operations on string using string libraries.
output:
The first occurrence of str2 is at : 8
The last occurrence of str2 is at : 21
str1 begins with : geeks
str1 does not end with : geeks
All characters in str are not upper cased
All characters in str1 are lower cased
The lower case converted string is : geeksforgeeks is for geeks
The upper case converted string is : GEEKSFORGEEKS IS FOR GEEKS
The swap case converted string is : gEEKSfORgEEKS IS FoR gEEkS
The title case converted string is : Geeksforgeeks Is For Geeks
output:
enter a string: Malayalam
PALLINDROME
3. Write a program to count the numbers of characters in the string and store them in a
dictionary data structure.
str=input("Enter a String")
dict = {}
for i in str:
dict[i] = str.count(i)
print (dict)
output:
Enter a String: guntur
{'g': 1, 'u': 2, 'n': 1, 't': 1, 'r': 1}
output:
enter the string: welcome to python
After splitting:[‘welcome’, ‘to’, ‘python’]
After joining: welcome-to-python
def Anagram_check(str1, str2):
# Strings are sorted and check whether both are matching or not
if(sorted(str1)== sorted(str2)):
print("Both strings are an Anagram.")
else:
print("Both strings are not an Anagram.")
str1 =input(“enter the first string”)
str2 =input(“enter the second string”)
print( "String value1 : ", str1 )
print( "String value2 : ", str2 )
Anagram_check(str1, str2)
Output:
enter the first string: abcd
enter the second string: bcda
String value1:abcd
String value2:bcda
Bothe strings are an Anagram
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set("aeiouAEIOU")
# Loop to traverse the alphabet in the given string
Output:
enter the string: abcde
No. of vowels : 2
7. Create a module with two functions one for finding Armstrong number, and second is for
testing whether the given string is palindrome or not. Write a python application to import
the above module some other application
def palindrome(st):
j = -1
flag = 0
for i in st:
if i != st[j]:
j = j - 1
flag = 1
break
j = j - 1
if flag == 1:
print("%s is NOT PALLINDROME", st)
else:
print("%s is PALLINDROME", st)
#create another file which imports the above module, let it be main.py
Output:
Enter the number to check it is Armstrong or not:153
Enter a string to check whether it is palindrome or not: abc
153 is Armstrong number
abc is NOT PALINDROME
#now create a file with name sample.py in same directory packagedemo with following code
x= int(input(“enter a number”))
y= int(input(“enter another number”))
str=input(“etner a string:”)
sum(x,y)
average(x,y)
converttolower(str)
converttoupper(str)
output:
enter a number: 4
enter another number:6
enter a string:abD
sum of the numbers is:10
average of the numbers is: 5
The lower case converted string is : abd
The upper case converted string is : ABD
f=open("myfile.txt", "w+")
for i in range(5):
f.write("this is line %d\r\n" %(i+1))
f.close()
f=open("myfile.txt", "r")
if f.mode=='r':
contents=f.read()
print(contents)
output:
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
10. Write Python script to copy file contents form one file to another
f=open("first.txt", "w+")
for i in range(5):
f.write("this is line %d\r\n" %(i+1))
f.close()
f1=open("first.txt", "r")
f2=open("second.txt", "w+")
if f1.mode=='r':
for line in f1:
f2.write(line)
f2.close()
print("contents of first file")
contents=f1.read()
print(contents)
f2=open("second.txt", "r")
print("contents of second file")
contents=f2.read()
print(contents)
f1.close()
f2.close()
output:
contents of first file
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
contents of second file
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
11. Write a python program that accepts file as an input from the user. Open the file and
count the number of times a character appears in the file.
output:
enter the file name:first.txt
enter the character to count the number of occurrences in the file:t
number of occurrences=5
Exercise 8:
1.Write a program that has a class Circle. Use a class variable to define the value of constant
PI. Use this class variable to calculate area and circumference of a circle with specific radius.
class Circle:
pi=3.14159
def __init__(self, radius):
self.radius=radius
print(“radius=%d”, self.radius)
def area(self):
return self.pi*self.radius**2
def circumference(self):
return2*self.pi*self.radius
c=Circle(10)
print(c.pi)
a=print(c.area())
cir=print(c.circumference())
print(“area=”)
print(a)
print(“circumference=”)
print(cir)
output:
3.14159
radius=10
area=314.159
circumference=62.906
output:
please add money in your account
3.Write a python program to validate given phone number is correct or not using regular
expression(phone numbers format can be +91-1234-567-890, +911234567890, +911234-
567890, 01234567890, 01234-567890, 1234-567-890, 1234567890)
import re
def validate_number(number):
if(re.search(r'^\+91-?\d{4}-?\d{3}-?\d{3}$|^0?\d{4}-?\d{3}-?\d{3}$',number)):
print("Valid Number")
else:
print("Invalid Number")
validate_number("+91-1234-567-890")
validate_number("+911234567890")
validate_number("+911234-567890")
validate_number("01234567890")
validate_number("01234-567890")
validate_number("1234-567-890")
validate_number("1234567890")
validate_number("12344567890")
validate_number("123-4456-7890")
Output:
Valid Number
Valid Number
Valid Number
Valid Number
Valid Number
Valid Number
Valid Number
Invalid Number
Invalid Number
4.Create a student table in python and insert at least 5 records and display the all table entries.
import sqlite3
sqliteConnection=sqlite3.connect('sql.db')
cursor=sqliteConnection.cursor()
cursor.execute("CREATE TABLE student(name char(20), rollno char(10), branch char(5));")
cursor.execute("""INSERT INTO student('name', 'rollno', 'branch') VALUES
('AAA','1234','CSE');""")
cursor.execute("""INSERT INTO student VALUES('BBB','5678','CSE');""")
cursor.execute("""INSERT INTO student VALUES('CCC','6789','CSE');""")
cursor.execute("""INSERT INTO student VALUES('DDD','7891','IT');""")
cursor.execute("""INSERT INTO student VALUES('EEE','3456','IT');""")
sqliteConnection.commit()
print('data entered successfully')
rows=cursor.execute(“SELECT * FROM student;")
print("student details:")
for row in rows:
print(row)
sqliteConnection.close()
if(sqliteConnection):
sqliteConnection.close()
print(“\nsqlite connection is closed”)
output:
data enetered successfully
student details:
('AAA','1234','CSE')
('BBB','5678','CSE')
('CCC','6789','CSE')
('DDD','7891','IT')
('EEE','3456','IT')
Sqlite connection is closed
5.Write a python program to read group of words into a string and print the results as which
words are ended with ‘at’ by using regular expression
import re
def checking(s1):
x=list(re.findall("\w+[at]", s1))
print(x)
s1=input("enter a string:")
checking(s1)
output:
enter a string: what is a bat
['what', 'bat']
6. Create a GUI application using tkinter where it will accept two numbers and when click the
submit button the addition of 2 numbers will be display in the sum field.
from tkinter import *
def sum():
a=int(t1.get())
b=int(t2.get())
c=a+b
t3.insert(0,c)
win=Tk()
win.geometry('250x250')
l3=Label(win,text="sum") l
3.grid(row=2,column=0)
t3=Entry(win)
t3.grid(row=2,column=1)
b1=Button(win,text="submit",command=sum) b1.grid(row=3,column=1)
win.mainloop()
output:
7. Design a GUI application using tkinter, it look likes