You are on page 1of 35

Exercise 1

1. Running instructions in interactive interpreter and a Python Script

>>>Print(“Hello world”)

2. Write a program to purposefully raise indentation error and correct it

>>>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

age=int(input(“enter the age”))


if age)>=18 :
print(“\n eligible for voting”)
else :
print(“\n not eligible for voting”)
output:

enter the age 20


eligible for voting

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:

Enter the number: 2012


Given Year is a leap Year

Exercise 3

1.Write a program to check whether given number is even or odd

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:

1, 0.5, 0.3333333333333333 0.25 0.2 0.16666666666666666 0.14285714285714285 0.125


0.1111111111111111 0.1

3.Write a program for displaying reversal of a number

num=int(input (“enter a number:”))


reversed_num=0
while num!=0:
digit=num%10
reversed_num=reversed_num*10+digit
num//=10
print(“reversed number:”+ str(reversed_num))

output:

enter a number: 1234


Reversed Number: 4321

4. Write a program for finding biggest number among 3 numbers

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
 
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
 
print("The largest number is",largest)
output:

Enter first number:10


Enter second number: 15
Enter third number:12
The largest number is 15

5.Write a program using a while loop that asks the user for a number, and prints a countdown
from that number to zero.

num=int(input("Enter your number"))


while(num>=0):
    print(num)
    num=num-1

output:

Enter your number 10


10 









0

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:

enter the list size:8


enter list of marks ranging from 0 to 50: 1 1 42 33 42 13 3 43
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
Exercise 4:

1.Implement python script to generate first N natural numbers.

num = int(input("Enter any number : "))

print("\nNatural numbers from 1 to", num)

for i in range(1, num + 1):


print(i, end=" ")

output:

Enter any number:5

Natural numbers from 1 to 5

12345

2. Implement python script to check given number is palindrome or not

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!

3. implement python script to print factorial of a number

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

4. Implement python script to print sum of N natural numbers

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

5. Implement Python script to check given number is Armstrong or not

num = int(input("Enter the number: ")) 


sum = 0 
temp = num 
while (temp > 0): 
    digit = temp % 10 
    sum += digit ** 3 
    temp //= 10if (num == sum): 
    print("Armstrong number") 
else: 
    print("Not an Armstrong number")
Output:
Enter the number:121
Armstrong number

6. implement python script to generate prime numbers up to n

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:

Enter the number till you want to print prime numbers: 8


2357

Exercise 5:

1.Define a function max_of_three() that takes three numbers as arguments and returns the
largest of them.

def maximum(a, b, c):


  
    if (a >= b) and (a >= c):
        largest = a
  
    elif (b >= a) and (b >= c):
        largest = b
    else:
        largest = c
          
    return largest
  
  
# Driven code 
a = 10
b = 14
c = 12
print(maximum(a, b, c))

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……..

3. write a python program to demonstrate all types of arguments in a function with


examples.

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)

4. Excise program on recursion and parameter passing techniques.

def sum(n):
if n > 0:
return n + sum(n-1)
return 0

result = sum(100)
print(result)

output:
5050

5.Define a function which generates Fibonacci series upto n numbers

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:

How many terms?5


0
1
1
2
3
5

6. Define a function that checks a given number is Armstrong or not

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")

num = int(input("Enter Number: "))


order = len(str(num))
Armstrong(num,order)

Output:
Enter Number:153
153 is an Armstrong number

7. Implement a python script for factorial of number by using recursion

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

8.Write function to compute gcd , lcm of two numbers

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

# Reading numbers from user


first = int(input("Enter first number: "))
second = int(input("Enter second number:"))

# Function call & displaying output HCF (GCD)


print('HCF or GCD of %d and %d is %d' %(first, second, find_gcd(first, second)))

# 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:

1.Finding the sum and average of given numbers using lists.

L = [4, 5, 1, 2, 9, 7, 10, 8]

# variable to store the sum of


# the list
count = 0

# Finding the sum


for i in L:
count += i

# divide the total elements by


# number of elements
avg = count/len(L)

print("sum = ", count)


print("average = ", avg)

output:
sum=46
average=5.75

2. To display the elements of list in reverse order

def Reversing(lst):
lst.reverse()
return lst

lst = [10, 11, 12, 13, 14, 15]


print("list ",lst)
print("reversed list",Reversing(lst))

output:
list [10, 11, 12, 13, 14, 15]
reversed list [15, 14, 13, 12, 11, 10]

3. Finding minimum and maximum elements in the list

A=[20, 30, 10, 45]


print("list:", A)
print("minimum element of the list", min(A))
print("maximum element of the list",max(A))

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

for item in data_list:


s=s-1
new_list[s] = item
return new_list

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]

6. Python program to explain the various operations on tuples.

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):

# Initializing count variable to 0


count = 0

# Creating a set of vowels


vowel = set("aeiouAEIOU")

# Loop to traverse the alphabetin the given string


for alphabet in str:

# If alphabet is present set vowel


if alphabet in vowel:
count = count + 1
print("No. of vowels :", count)

# Driver code
str=input("enter a string")

# Function Call
vowel_count(str)

output:
enter a stringabcdef
No. of vowels:2

8. Python program to check common letters in tow input strings

#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:

Enter Your first string: agbcd


Enter Your second string: abetr
The common letters are:
a
b

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

10. Python program to Add a key-value pair to the Dictionary

# Python Program to Add Key-Value Pair to a Dictionary using update

key = input("Please enter the Key : ")


value = input("Please enter the Value : ")

myDict = {}

# Add Key-Value Pair to a Dictionary in Python


myDict.update({key:value})
print("\nUpdated Dictionary = ", myDict)

output:
Please enter the Key: k1
Please enter the Value:10
Updated Dctionary={‘k1’:’10’}

# Python Program to Add Key-Value Pair to a Dictionary

key = input("Please enter the Key : ")


value = input("Please enter the Value : ")

myDict = {}

# Add Key-Value Pair to a Dictionary in Python


myDict[key] = value
print("\nUpdated Dictionary = ", myDict)

output:
Please enter the Key: k1
Please enter the Value:10
Updated Dctionary={‘k1’:’10’}

11. Python program to concatenate to dictionaries into one

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}

12. Python program to check if a given key exists in a Dictionary or not


Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("The given dictionary : ",Adict)
check_key = "Wed"
if check_key in Adict.keys():
print(check_key,"is Present.")
else:
print(check_key, " is not Present.")

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.

str = "geeksforgeeks is for geeks"


str2 = "geeks"
 
# using find() to find first occurrence of str2 returns 8
print ("The first occurrence of str2 is at : ", end="")
print (str.find( str2, 4) )
 
# using rfind() to find last occurrence of str2 returns 21
print ("The last occurrence of str2 is at : ", end="")
print ( str.rfind( str2, 4) )
# using startswith() to find if str starts with str1
if str1.startswith(str):
        print ("str1 begins with : " + str)
else : print ("str1 does not begin with : "+ str)
 
# using endswith() to find if str ends with str1
if str1.endswith(str):
    print ("str1 ends with : " + str)
else :
    print ("str1 does not end with : " + str)
# checking if all characters in str are upper cased
if str.isupper() :
    print ("All characters in str are upper cased")
else :
    print ("All characters in str are not upper cased")
 
# checking if all characters in str1 are lower cased
if str1.islower() :
    print ("All characters in str1 are lower cased")
else :
    print ("All characters in str1 are not lower cased")
# Python code to demonstrate working of upper(), lower(), swapcase() and title()
# Converting string into its lower case
str1 = str.lower();
print (" The lower case converted string is : " + str1)
 
# Converting string into its upper case
str2 = str.upper();
print (" The upper case converted string is : " + str2)
 
# Converting string into its swapped case
str3 = str.swapcase();
print (" The swap case converted string is : " + str3)
 
# Converting string into its title case
str4 = str.title();
print (" The title case converted string is : " + str4)

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

2. Implement Python script to check given string is palindrome or not


st = intput(“enter a string:”)
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("NOT PALLINDROME")
else:
    print("PALLINDROME")

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}

4. Write a program to use spilt and join methods in the string.


def spit_string(string):
#splitting based on space delimiter
List_string=string.split(‘ ‘)
return list_string
def join_string(list_string):
#joining vased on ‘–‘ delimiter
string=’-‘.join(list_string)
return string
string=input(“enter the string:”)
list_string=split_string(string)
print(“After splitting:”, list_string)
res_string=join_string(list_string)
print(“After joining:”,res_string)

output:
enter the string: welcome to python
After splitting:[‘welcome’, ‘to’, ‘python’]
After joining: welcome-to-python

5. Python program to detect if two strings are Anagrams

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

6. Python program to count the number of vowels in a string.

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

    for alphabet in str:


      
        # If alphabet is present in set vowel
        if alphabet in vowel:
            count = count + 1
      
    print("No. of vowels :", count)
      
# Driver code 
str = input(“enter the string:”)
  
# Function Call
vowel_count(str)

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

# create a file containing two functions Armstrong and palindrome , module.py


  
def armstrong(num):
  sum = 0 
temp = num 
while (temp > 0): 
   digit = temp % 10 
    sum += digit ** 3 
    temp //= 10
if (num == sum): 
   print("%d is Armstrong number", num) 
else: 
    print("%d is Not an Armstrong number", num)

  
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

from module import *


num=int(input(“enter the number to check it is Armstrong or not:”))
str=input(“etner a string to check whether it is palindrome or not:”)
armstrong(num)
palindrome(str)

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

8. Create a python package contains 2 modules of your name functions(minimum 2 functions


in each module) and import the packages and modules in other applications which perform
some task.

#first create a directory named packagedemo


#create following files in the folder
#create a file module1.py in packagedemo directory with following content
def sum(x,y)
print(“sum of the numbers is:”)
print(x+y)
def average(x,y)
print(“average of the numbers is:”)
print((x+y)/2)

#crate another file module2.py in packagedemo with following content


def converttolower(str):
str1 = str.lower();
print (" The lower case converted string is : " + str1)
 
def converttouppler(str):
str2 = str.upper();
print (" The upper case converted string is : " + str2)
#create an empty file with name _init_.py in packagedemo then place following initializing
code

from module1 import sum, average


from module2 import converttolower, converttoupper

#now create a file with name sample.py in same directory packagedemo with following code

from module1 import sum, average


from module2 import converttolower, converttoupper

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

9. Write a python script to display file contents

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.

filename=input(“enter the file name:”)


f1=open(filename, "r")
if f1.mode=='r':
contents=f1.read()
letter=input("enter the character to count the number of occurrences in the file ")
count=contents.count(letter)
print("number of occurrences =%d”, count)
else:
print("file does not exist ")

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

2.Program to raise value error and handle using try-except

# try for unsafe code


try:
    amount = 1999
    if amount < 2999:
          
        # raise the ValueError
        raise ValueError("please add money in your account")
    else:
        print("You are eligible to purchase DSA Self Paced course")
              
# if false then raise the value error
except ValueError as e:
        print(e)

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')

l1=Label(win,text="First Number") l1.grid(row=0,column=0)


t1=Entry(win)
t1.grid(row=0,column=1)

l2=Label(win,text="Second Number") l2.grid(row=1,column=0)


t2=Entry(win)
t2.grid(row=1,column=1)

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

You might also like