0% found this document useful (0 votes)
0 views

python_file

The document outlines various programming experiments conducted by a student named Akshay Sharma at Guru Nanak Dev University, covering arithmetic, assignment, comparison, logical, bitwise, membership, identity operators, and built-in string and dictionary methods. Each experiment includes input examples, explanations of the operations, and their corresponding outputs. Additionally, it features conditional statements and a program for calculating discounts based on purchase amounts.

Uploaded by

Tanya Pathak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

python_file

The document outlines various programming experiments conducted by a student named Akshay Sharma at Guru Nanak Dev University, covering arithmetic, assignment, comparison, logical, bitwise, membership, identity operators, and built-in string and dictionary methods. Each experiment includes input examples, explanations of the operations, and their corresponding outputs. Additionally, it features conditional statements and a program for calculating discounts based on purchase amounts.

Uploaded by

Tanya Pathak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Guru Nanak Dev University

Regional Campus, Jalandhar

file
Name: Akshay Sharma
Course: B. Tech ENC
Semester: First
Submitted to: Dr. Butta Singh
Experiment-1

Arithmetic Operators

● Addition Operators
Input:
a=5
b=10
a+b (Gives the sum of given values)

Output:
15

● Subtraction Operators
Input:
p=20
q=4
p-q (Gives difference of given values)

Output:
16

● Multiplication Operators
Input:
m=6
n=9
m*n (Gives product of given two numbers)

Output:
54

● Division Operator
Input:
o=50
p=10
o/p (Gives the answer obtained by dividing the given values)
Output:
5.0
● Modulus Operator
Input:
c=90
d=7
c%d (Gives the remainder obtained by dividing given two values)

Output:
6

● Exponential Operator
Input:
x=9
y=5
x**y (Gives the value obtained by powering the value of x w.r.t y)

Output:
59049

● Floor division Operator


Input:
s=10
t=3
s//t (Gives only the first whole integer obtained by dividing two numbers and neglect all
other decimal place values)

Output:
3
Experiment-2
Assignment Operators

● '='
Input:
a=5 (Assigns a value 5 to a variable 'a')

Output:
5

● '+=' Add
Input:
x=5
x+=3 (Adds the value to the previously defined value of a variable or can be defined as x=x+3)

x
Output:
8

● '-=' Subtract
Input:
s=10
s- =4 (Subtracts the given value from defined value of variable or can be defined as s=s-4)

s
Output:
6

● '/=' Divide
Input:
c=60
c/=4 (Divides the variable defined value with this given value or can be defined as c=c/4)
c
Output:
15.0

● '*=' Multiply
Input:
y=70
y*=8 (Multiplies this given value with the previously defined value of a variable)
y

Output:
560

● %= Modulus
Input:
b=50
b%=6 (Gives the remainder by dividing this value with the originally defined of a variable)
b

Output:
2

● '//=' Floor Division


Input:
p=20
p//=3 (Gives only the the first integer obtained by diividing this value with the previously
assigned value of a variable)
p

Output:
6

● '**=’ Exponent
Input:
m=4
m**=3 (Gives the output by taking this value as the power for the previously assigned value
of variable or m=m**3)
m
Output:
64
Experiment-3

Comparison Operators

● Equal(==)
Input:
x=5
y=4
x==y (Gives true as output if value of both variables are equal to each other otherwise gives
false as an output)

Output:
False

● Not Equal(!=)
Input:
a=5
b=4
a!=b (Gives false as an output if value of both variables are equal to each other otherwise gives
true as an output)

Output:
True

● Greater than(>)
Input:
p=10
q=8
p>q (Gives true as an output in this case if p is greater than q and gives false as an output if p
is less than q)

Output:
True

● Less than(<)
Input:
m=50
n=5
m<n (Gives false as an output in this case if p is greater than q and gives true as an output if p
is less than q)
Output:
False

● Greater than or equal to(>=)


Input:
c=40
d=40
c>=d (Gives true as an output if value of c is either greater or equal to value of d or else gives
false as an output)

Output:
True

● Less than or equal to(<=)


Input:
s=29
t=30
s<=t (Gives true as an output if value of s is either smaller or equal to value of t or else gives
false as an output)

Output:
True
Experiment-4

Logical Operators

● and
Input:
x=10
x>5 and x<20 (Returns true only if both the statements are correct/true)

Output:
True

● or
Input:
a=5
b=4
a>6 or b<2 (Returns true as an output if one of the statements are true or else returs false)

Output:
False

● not
Input:
p=15
not(p!=10) (Returns false if statement is correct and vice-versa. In short it reverse the
original) output

Output:
False
Experiment-5

Bitwise Operators
● '& Binary AND'
Input:
a=5
b=10
a&b (Operator copies a bit to the result,if it exist in both operands)

Output:
0

● '| Binary OR'


Input:
x=2
y=4
x|y (It copies a bit, if it exists in either operands )

Output:
6

● '^ Binary XOR'


Input:
b=3
c=2
b^c (It copies the bit, if it is set in one operands but not both)

Output:
1

● '~ Binary Ones Complement'


Input:
d=6
(~d) (It is unary and has the effect of 'flipping' bits)
Output:
-7

● '<< Binary left shift'


Input:
a=20
a<<240 (The left operand's value is moved left by the number of bits specified by right operands)

Output:
35336941295567686591665950014858370316549677937512379162432124025852395520

● '>> Binary Right shift'


Input:
a=20
a>>240 (The left operand's value is moved right by the number of bits specified by right operands)

Output:
0
Experiment-6

Membership Operators

● 'in'
Input:
x=[1,2,3,4,5,6]
6 in x (Evaluates true, if it finds a variable in the specified sequence and false otherwise)

Output:
True

● 'not in'
Input:
x=[1,2,3,4,5,6]
6 not in x
(Evaluates true, if it does not finds a variable in the specified sequence and false otherwise)

Output:
False
Experiment-7

Identity Operators

● 'is'
(Returns true if both variables are the same object)
Input:
x=[1,2,3,4,5]
y=[1,2,3,4,5]
z=x
x is z (Returns True because z is the same object as x)

Output:
True

Input:
x is y (Returns False because x is not the same object as y, even if they have the same content)

Output:
False

● 'is not'
( Returns true if both variables are not the same object)
Input:
x=[1,2,3,4,5]
y=[1,2,3,4,5]
z=x
x is not z (Returns False because z is the same object as x)

Output:
False

Input:
x is not y (Returns True because x is not the same object as y, even if they have the same content)

Output:
True
Experiment-8

Built-in String Methods


Strings: - Strings are basically used to Define
alphanumeric character.
● String Capitalize() Method

Input:
str='punjab'
str.capitalize() (Returns the copy of string with first character capitalized)

Output:
'Punjab'

● String Centre() Method

Input:
str='Jalandhar'
str.center(50,'*') (Returns a centered string)

Output:
'********************Jalandhar*********************'

● String Endswith() Method

Input:
a='apple'
a.endswith('e')

(Returns true if the string ends-with the specified suffix/character and else returns false)

Output:
True

● String isalpha() Method

Input:
str='apple'
str.isalpha() (Returns true if all the characters in the string are alphabets and else returns false)

Output:
True
● String isdigit() Method

Input:
str='123a'
str.isdigit() (Returns true if the string consits of only digits and else returns false)

Output:
False

● String isalnum() Method

Input:
str='apple123'
str.isalnum()

(Returns true if the string consits of either digits or alphabets or both and else returns false)

Output:
True

● String islower() Method

Input:
str='Jalandhar'
str.islower()

(Returns True only if all the characters in the strings are of Lower-case and else returns false)

Output:
False

● String isupper() Method

Input:
str='JALANDHAR'
str.isupper()

(Returns True only if all the characters in the strings are of Upper-case and else returns false)

Output:
True
● String isspace() Method

Input:
str='An appple a day keeps the doctor away'
str.isspace() (Returns True if all characters in the string are whitespaces)

Output:
False

Input:
str=' '
str.isspace(
)

Output:
True

● String join() Method

Input:
str='Chandigarh'
str.join("''") (Joins the elements of an iterable to the end of the string)

Output:
"'Chandigarh'"

● String lower() Method

Input:
str='APPLE'
str.lower() (Converts all the alphabetic characters of a string to lower case)

Output:
'apple'

● String upper() Method

Input:
str='appLe'
str.upper() (Converts all the alphabetic characters of a string to upper case)

Output:
'APPLE'
● String max() Method

Input:
str='Punjab'
max(str) (Returns the maximum alphabetical character from the string)

Output:
'u'

● String min() Method

Input:
str='Jalandhar'
min(str) (Returns the minimum alphabetical character from the string)

Output:
'J'

● String replace() Method

Input:
str='Chandigarh'
str.replace('Chandigarh','Jalandhar')

(Replaces the character in the string with new specified character)

Output:
'Jalandhar'

● String lstrip() Method

Input:
str=' Jalandhar
' str.lstrip()

(Returns the copy of string in which all chars have been stripped from the beginning of the string)

Output:
'Jalandhar '
● String strip() Method

Input:
str=' Jalandhar
' str.strip()

(Returns the copy of string in which all chars have been stripped from the beginning and end of the
string)

Output:
'Jalandhar'

● String maketrans() and translate() Method

Input:
v='aeiou'
num='12345'
str='guru nanak dev university'
trans=str.maketrans(v,num)

(The maketrans() method returns a translation table to be used in translations)

str.translate(trans) (Returns a translated string)

Output:
'g5r5 n1n1k d2v 5n3v2rs3ty'

● String split() Method

Input:
str="Guru nanak dev university"
str.split() (Splits the string at the specified separator, and returns a list)

Output:
['Guru', 'nanak', 'dev', 'university']

● String splitlines() Method

Input:
str="Guru nanak dev university"
str.splitlines() (Splits the string at line breaks and returns a list)

Output:
['Guru nanak dev university']
● String swapcase() Method

Input:
str='Jalandhar Is Beautiful City'
str.swapcase() (Change the upper case characters to lower case and vice-versa)

Output:
'jALANDHAR iS bEAUTIFUL cITY'

● String zfill() Method

Input:
str.zfill(0)

Output:
'Jalandhar Is Beautiful City'

● String isdecimal() Method

Input:
str='1.2654'
str.isdecimal() (Returns True if all characters in the string are decimals)

Output:
False
Experiment-9
Built-in Dictionary Methods

● Dictionary str() Method

Input:
dict={'a':1 , 'b':2 , 'c':3}
str(dict) (Produces a printable string representation of a dictionary)

Output:
"{'a': 1, 'b': 2, 'c': 3}"

● Dictionary clear() Method

Input:
dict={'a':1 , 'b':2 , 'c':3}
dict.clear() (Removes all items from the dictionary)
dict

Output:
{}

● Dictionary copy() Method

Input:
dict={'a':1 , 'b':2 , 'c':3}
x=dict.copy() (Copies the specified
dictionary) x

Output:
{'a': 1, 'b': 2, 'c': 3}
● Dictionary fromkeys() Method

Input:
dict={'a':1 , 'b':2 , 'c':3}
dict1=(5,6)
dict.fromkeys(dict,dict1) (Creates a new dictionary with keys from seq and values set to value)

Output:
{'a': (5, 6), 'b': (5, 6), 'c': (5, 6)}

● Dictionary get() Method

Input:
dict={'a':1 , 'b':2 , 'c':3}
dict.get('a') (Returns the value of the specified key)

Output:
1

● Dictionary update() Method

Input:
dict={'a':1 , 'b':2 , 'c':3}
dict1={'z':3,'y':4}
dict2=dict.update(dict1)

[Updates the dictionary with the specified key-value pairs (This method does not return any value)]
Experiment-10

Conditional Statements IF-ELSE and their


Programs

● If-Else ladder
Input:
x=input('Enter First Number')
y=input('Enter Second Number')
if x>y:
print(x,'is higher than',y)
else:
print(y,'is higher than',x)

Output:
Enter First Number7
Enter Second Number9
9 is higher than 7

Input:
x=int(input('Enter First Number'))
y=int(input('Enter Second Number'))
if x>y:
print(x,'is higher than',y)
else:
print(y,'is higher than',x)
print('Good Bye')

Output:
Enter First Number8
Enter Second Number4
8 is higher than 4

● ELIF

Input:
x=int(input('Enter First Number'))
y=int(input('Enter Second Number'))
if x>y:
print(x,'is higher than',y)
elif x<y:
print(y,'is higher than',x)
elif x==y:
print(x,'is equal to',y)
else:
print('Good Bye')

Output:
Enter First Number9
Enter Second Number9
9 is equal to 9

● Nested If

Input:
num=int(input('Enter Number'))
if num%2==0:
if num%3==0:
print('Divisible By 2 and3')
else:
print('divisible By 2 not by 3')
else:
if num%3==0:
print('divisible by 3 not by 2')
else:
print('not divisible by 2 and 3')

Output:
Enter Number66
Divisible By 2 and3

WAP to offer discount (D) on purchase (P)


1) D=10% for total purchase greater than or equal to 1000 Rs

2) D=5% for total purchase greater than or equal to 700 Rs

3) D=2% for total purchase greater than or equal to 500 Rs

4) No discount if pruchase is less than 500

Rs Also show amount to pay and savings

Input:
n=int(input("Enter the total purchase amount: "))
if n>=1000:
D=0.1*n
print("Congrats you saved Rs",D)
print("Amount to be paid is",n-D)
elif n>=700 and n<1000:
D=0.05*n
print("Congrats you saved Rs",D)
print("Amount to be paid is",n-D)
elif n>=500 and n<700:
D=0.02*n
print("Congrats you saved Rs",D)
print("Amount to be paid is",n-D)
else:
print("Sorry you didn't get any discount")
print("Amount to be paid is",n)

Output:
Enter the total purchase amount: 600
Congrats you saved Rs 12.0
Amount to be paid is 588.0

WAP to accept a number between 1 to 100 and check


using nested-if statement
Input:
n=int(input("Enter a number between 1 to 100: "))
if n>=1 and n<=100:
if n%2==0:
print("The number",n,"is an even number")
else:
print("The number",n,"is an odd number")
else:
print("Sorry your number doesn't lie between 1 to 100")

Output:
Enter a number between 1 to 100: 65
The number 65 is an odd number

WAP to accept a number between 1 to 100 and check


using nested-if statement

Number is divisible by 2 and 3

Number is divisible by 2 but not by 3


Number is divisible by 3 but not by 2

Number is not divisible by 2 and 3

Input:
n=int(input("Enter a number: "))
if n%2==0 and n%3==0:
print("Number is divisible by 2 and 3")
elif n%2==0 and n%3!=0:
print("Number is divisible by 2 but not by 3")
elif n%2!=0 and n%3==0:
print("Number is divisible by 3 but not by 2")
else:
print("Number is not divisible by 2 and 3")

Output:
Enter a number: 35
Number is not divisible by 2 and 3

WAP to check given char is a vowel


Input:
n=input("Enter a character: ")
if n=='a'or n=='e' or n=='i' or n=='o' or n=='u':
print("Enterd char",n,"is a vowel")
else:
print("Enterd char",n,"is not a vowel")

Output:
Enter a character: a
Enterd char a is a vowel

WAP to find the largest of three numbers

Input:

n1=int(input("Enter num1: "))


n2=int(input("Enter num2: "))
n3=int(input("Enter num3: "))
if n1>n2 and n1>n3:
print(n1,"is greatest")
elif n2>n1 and n2>n3:
print(n2,"is greatest")
else:
print(n3,"is greatest")

Output:
Enter num1: 1
Enter num2: 2
Enter num3: 3
3 is greatest

WAP to check given year is a leap year or not


Input:
n=int(input("Enter a year: "))
if n%4==0:
print(n,"is a leap year")
else:
print(n,"is not a leap year")

Output:
Enter a year: 2020
2020 is a leap year

WAP to check if the given year is leap or not

Input:
x=int(input('Enter the year here '))
if x%4==0 or x%400==0 and x%100!=0:
print('Year',x,'is a Leap Year')
else:
print('Year',x,'is not a Leap Year')

Output:
Enter the year here 2007
Year 2007 is not a Leap
Year

WAP to swap any two numbers


Input:
n1=int(input('The first number is '))
n2=int(input('The second number is '))
s=n1
n1=n2
n2=s
print('The First Swapped Number is',n1)
print('The Second Swapped Number is',n2)
Output:
The first number is 7
The second number is 92
The First Swapped Number is 92
The Second Swapped Number is 7

Given a point (x,y). WAP to find the Quadrant of given


(x,y) in x-y plane

Input:
x=int(input("Enter the value of x: "))
y=int(input("Enter the value of y: "))
if x>0 and y>0:
print("Point(x,y) lies in the first quadrant")
elif x<0 and y>0:
print("Point(x,y) lies in the second quadrant")
elif x<0 and y<0:
print("Point(x,y) lies in the third quadrant")
else:
print("Point(x,y) lies in the fourth quadrant")

Output:
Enter the value of x: 1
Enter the value of y: 2
Point(x,y) lies in the first quadrant
Experiment-11

List-Methods

List:- These are ordered sequence of Mixed data. These can be altered
as they are mutable.
Input:
thislist = ["apple", "banana", "cherry"]

print(thislist)

Output:
[‘apple’,’banana’,’cherry’]

● append()
Input:
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange") #Adds the value ‘orange’ to list ‘fruits’

print(fruits)

Output:
['apple', 'banana', 'cherry', 'orange']

● clear()
Input:
fruits = ['apple', 'banana', 'cherry']
fruits.clear() #Clears the list
‘fruits’

print(fruits)

Output:
[]
● index()
Input:
fruits = ['apple', 'banana', 'cherry']
x=fruits.index(“apple”) # Returns the index of the first element with the specified

value x

Output:
0

● count()
Input:
fruits = ['apple', 'banana', 'cherry']
x=fruits.count(“apple”)

print(x)

#Returns the number of times ‘apple’ is repeated in list ‘fruits’

Output:
1

● insert()
Input:
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1,”orange”)

print(x)

#The insert() method inserts the specified value at the specified position

Output:
['apple', 'orange' ,'banana', 'cherry']
Experiment-12

Tuples and Sets

Tuples:- These are immutable but same as lists. These are enclosed in
brackets. A tuple is a collection which is ordered and unchangeable.
Input:
thistuple = ("apple", "banana", "cherry")

print(thistuple)

Output:
('apple' ,'banana', 'cherry')

Sets:- Sets are used to store multiple items in a single variable. A set is a
collection which is both unordered and unindexed. Sets are written with curly
brackets. Sets cannot have two items with the same value.

Input:

thisset = {"apple", "banana", "cherry"}


print(thisset)

Output:
{'apple' ,'banana', 'cherry'}
Experiment-13

While Loops

It is mainly used to repeat the block of code. It repeats the block


of code for a no. of times until the certain result is met.
Eg:-
Input:
i=1

while i < 6:

print(i)

i += 1

Output:
1

WAP to print a table using While Loop

Input:
x=int(input("Enter a number: "))
i=1
while i<=10:
print(x,"X",i,"=",x*i)
i=i+1

Output:
Enter a number: 7
7X1=7

7 X 2 = 14

7 X 3 = 21

7 X 4 = 28

7 X 5 = 35

7 X 6 = 42

7 X 7 = 49

7 X 8 = 56

7 X 9 = 63

7 X 10 = 70

WAP to find the Factorial of a given number


Input:
x=int(input("Enter a number: "))
i=1
while
x>0:
i=i*x
x=x-1
print("Factorial=",i)

Output:
Enter a number: 5

Factorial= 120

WAP to find the sum of all numbers present in an integer

Input:
x=int(input('Enter the integer: '))
s=0
while x!=0:
s=s+(x%10)
x=int(x/10)
else:
print('Sum is: ',s)
Output:
Enter the integer: 563

Sum is: 14
Experiment-14

For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).

This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

WAP to check user defined number is a Prime number


Input:

x=int(input('Enter a number: '))


p=False
if x>1:
for i in range(2,x):
if x%i!=0:
p=True
else:
p=False
break

else:
print("Entered number is not a prime number")

if p==True:
print("The given number is prime")
else:
print("The given number is not prime")

Output:
Enter a number: 23
The given number is prime
WAP to print a table using For Loop

Input:
x=int(input('Enter a number: '))
print('Table of',a,'is printed below')
for i in range(1,11):
print(x,"X",i,"=",x*i)

Output:
Enter a number: 4
Table of 4 is printed below
4X1=4
4X2=8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
4 X 9 = 36
4 X 10 = 40

WAP to print a list in order

Input:
x=[1,3,2,4,5,7,6,9,7,8,0]
for i in x:
print(i)

Output:
1
3
2
4
5
7
6
9
7
8
0
WAP to print a list in reverse order

Input:
x=[1,3,2,4,5,7,6,9,7,8,0]
x.reverse()
for i in x:
print(i)

Output:
0
8
7
9
6
7
5
4
2
3
1

WAP to find total number of digits,uppercase &


lowercase letters present in a sentence

Input:
x=input("Enter a sentence: ")
u=0
v=0
w=0
for i in x:
if i.isupper():
u=u+1
elif i.islower():
v=v+1
elif i.isdigit():
w=w+1

print("The number of uppercase letter in the sentence is",u)


print("The number of lowercase letter in the sentence is",v)
print("The number of digits in the sentence is",w)

Output:
Enter a sentence: I am Rajanya Joshi currently studying Btech CSE from GNDU RC
The number of uppercase letter in the sentence is 13
The number of lowercase letter in the sentence is 37
The number of digits in the sentence is 0
WAP to Find the sum of odd and even numbers upto a
user defined range

Input:
x=int(input("Enter the lower range: "))
y=int(input("Enter the upper range: "))
u=0
v=0
for i in range(x,(y+1)):
if i%2==0:
u=u+i
else:
v=v+i

print("The sum of odd numbers in the range",x,"-",y,"is",v)


print("The sum of evem numbers in the range",x,"-",y,"is",u)

Output:
Enter the lower range: 1
Enter the upper range: 10
The sum of odd numbers in the range 1 - 10 is 25
The sum of evem numbers in the range 1 - 10 is 30

WAP to report the maximum salary from


following dictionary:
{'Ram':{'salary':10000,'age':30,'height':6}, 'Aman':{'salary':12000,'age':32,'height':5.8,
'Raman':{'salary':15000,'age':31,'height':5.6}}}

Input:
d={'Ram':{'salary':10000,'age':30,'height':6},'Aman':{'salary':12000,'age':32,'height':5.8},'Raman':{'sal
ary':15000,'age':31,'height':5.6}}
sal=[]
for v in d.values():
sal.append(v['salary'])
print(max(sal))

Output:
15000
Experiment-15

Mathematical Function

Input:
s=-5
abs(s)

Output:
5

Input:
s=2+3j
abs(s)

Output:
3.605551275463989

Input:
s=3.56
import math
math.ceil(s)

Output:
4

Input:
s=4.12
import math
math.ceil(s)

Output:
5

Input:
s=4.12
math.ceil(s)

Output:
5
Input:
math.exp(2)

Output:
7.38905609893065

Input:
s=3.56
math.fabs(s)

Output:
3.56

Input:
s=3.14
math.floor(s)

Output:
3

Input:
math.ceil(s)

Output:
4

Input:
math.log(100)

Output:
4.605170185988092

Input:
math.log10(100)

Output:
2.0

Input:
max(1,2,54,2,6,3,7,s)

Output:
54
Input:
s=3.14
s1=math.modf(s)

Input:
s1 tuple

Output:
(0.14000000000000012, 3.0)

Input:
s1[0]

Output:
0.14000000000000012

Input:
s1[1]

Output:
3.0

Input:
pow(2,3)

Output:
8

Input:
s=3.1231444
round(s)

Output:
3

Input:
round(s,4)

Output:
3.1231

Input:
s=9
math.sqrt(s)
Output:
3.0

WAP to find the area and perimeter of a circle

Input:

x=int(input('Enter the radius:'))


import math
p=math.pi
A=p*x*x
print('Area of circle is ',A)
P=2*p*x
print('Perimeter of circle is ',P)

Output:
Enter the radius:7
Area of circle is 153.93804002589985
Perimeter of circle is 43.982297150257104
Experiment-16

File Handling

File handling is an important part of any web


application. Python has several functions for creating,
reading, updating, and deleting files.

● Open() Function

f = open("demofile.txt") #Opens file naming demofile.txt for read only

● Read() file

Suppose demofile.txt has following content in it:


Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

Input:
f = open("demofile.txt", "r") #’r’ signifies file should be in read only
format print(f.read())

Output:
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
● Writing or creating a file

Suppose demofile.txt has following content in it:


Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

Input:
f = open("demofile.txt", "a") #’a’ signifies that content of the file should be appended
f. write("Have a Good Day!")
f.close()
f = open("demofile.txt", "r")
print(f.read())

Output:
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!Have a Good Day!

Input:
f = open("demofile.txt", "w")

#’w’ signifies that content of the file should be removed and new content is to be added

f. write("Have a Good Day!")


f.close()
f = open("demofile.txt", "r")
print(f.read())

Output:
Have a Good Day!

● Deleting a file

Suppose demofile.txt has following content in it:


Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

Input:
import os
os.remove("demofile.txt") #This will delete your file naming ‘demofile.txt’
Experiment-17

Some Programs Related To Matrix


Problems

WAP to multiply two matrices

Input:

a=[[1,2,3],[5,6,7]]
b=[[5,2],[3,2],[4,2]]
multp=[[0,0],[0,0]]
m=0
k=0
for i in range(0,len(a)):
for j in range(0,len(b[0])):
for k in range(0,len(b)):
multp[i][j]=multp[i][j]+a[i][k]*b[k][j]
print(multp[i][j])
print(multp)

Output:
5
11
23
2
6
12
25
43
71
10
22
36
[[23, 12], [71, 36]]

WAP to add two matrices

Input:
a=[[1,2,3],[4,5,6],[7,8,9],[1,2,3]]
b=[[9,8,7],[3,2,1],[6,5,4],[3,4,1]]
sum1=[[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
for i in range(0,len(a)):
for j in range(0,len(a[0])):
sum1[i][j]=a[i][j]+b[i][j]
print(sum1)
Output:
[[10, 10, 10], [7, 7, 7], [13, 13, 13], [4, 6, 4]]

WAP to find transpose of a matrix

Input:
s=[[1,2,3],[4,5,6],[7,8,9]]
trans_s=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(0,len(s)):
for j in range(0,len(s[0])):
trans_s[j][i]=s[i][j]
print(trans_s)

Output:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

You might also like