0% found this document useful (0 votes)
11 views36 pages

Python Programming Basics: I/O, Loops, Functions

Uploaded by

rashadsk251
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views36 pages

Python Programming Basics: I/O, Loops, Functions

Uploaded by

rashadsk251
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

WEEK 1: Input And Output

(A) AIM: Write a program to find the largest element among three Numbers.
OBJECTIVE:

IF Statement
The if statement is used to check a condition.
If the condition is true, Python executes the block of code under it.
Syntax
if condition:
# code to run when condition is true

ELIF Statement (else if)


elif is used when you want to check another condition
but only if the previous if condition was false.
Syntax
elif another_condition:
# code to run when this condition is true

ELSE Statement
else is used when none of the previous conditions are true.
It acts as a final fallback.

Syntax
else:
# code to run when all conditions above are false

Full Syntax Together

if condition1:
# code
elif condition2:
# code
elif condition3:
# code
else:
# code
4|P age
Gayatri Vidya Parishad College of Engineering (Autonomous)
SOURCE CODE:

a, b, c = map(int, input("Enter 3 numbers: ").split())


if a >= b and a >= c:
print("Largest:", a)
elif b >= a and b >= c:
print("Largest:", b)
else:
print("Largest:", c)

OUTPUT:

Enter 3 numbers: 10 25 7
Largest: 25

(B). AIM: Write a program to print the sum of all the even numbers in the range
1 - 50 and print the even sum.

OBJECTIVE:
Loops let you run the same block of code many times.
Python has two main loops:
1. for loop
 Used to repeat code for each item in something (like a list, string, or range).
 It uses the keyword in to go through items one by one.
 Syntax:

for variable in sequence:


# code

2. while loop
 Repeats code as long as a condition is true.
 Syntax:

while condition:
# code

What is range?
range() is a built-in function that creates a sequence of numbers.
It is often used in for loops when you want to repeat something a specific number of times.
range(stop)
range(start, stop)

5|P age
Gayatri Vidya Parishad College of Engineering (Autonomous)
range(start, stop, step)
Example idea (not code): “Repeat 5 times” → use range(5)

Use of the keyword in


The keyword in tells the loop to go through each item in a sequence.
It means, taking each element from this list/string/range one by one.

SOURCE CODE:

total = 0
for i in range(1, 51):
if i % 2 == 0:
total += i
print("Even sum:", total)

OUTPUT:
Even sum: 650

(C) AIM: Write a Program to display all prime numbers within an interval of
given X1 & X2.

OBJECTIVE:
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.

SOURCE CODE:

x1 = int(input("Start: "))
x2 = int(input("End: "))
for n in range(x1, x2+1):
if n > 1:
for i in range(2, int(n**0.5)+1):
if n % i == 0: break
else: print(n)

OUTPUT:
Start: 10
End: 20
11
13
17
19

6|P age
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK-2: Variables and Functions
Python Functions
Definition:A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
Example:
def my_function():
print("Hello from a function")

Calling a Function: To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print("Hello from a function")
my_function()

Arguments
Information can be passed into functions as arguments.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
Example:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")

Parameters or Arguments:
The terms parameter and argument can be used for the same thing: information that are
passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.

Default Parameter Value:


If we call the function without argument, it uses the default value:
Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")

7|P age
Gayatri Vidya Parishad College of Engineering (Autonomous)
my_function()
my_function("Brazil")

Return Values:
To let a function return a value, use the return statement:
Example:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))

The pass Statement:


function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.
Example:
def myfunction():
pass

(A). AIM: Write a program to swap two numbers without using a temporary
variable.

SOURCE CODE:
a, b = map(int, input("Enter a and b: ").split())
a, b = b, a
print("After swap:", a, b)

OUTPUT:
Enter a and b: 5 9
After swap: 9 5

(B). AIM: Write a program to define a function with multiple return values.

SOURCE CODE:
def calc(x, y):
return x+y, x-y, x*y

x = int(input())
y = int(input())
print(calc(x, y))

8|P age
Gayatri Vidya Parishad College of Engineering (Autonomous)
OUTPUT:
10
5
(15, 5, 50)

(C). AIM: Write a program to define a function using default arguments.

SOURCE CODE:
def greet(name="User", msg="Hello"):
print(msg, name)

name = input("Enter name: ")


greet(name or "User")

OUTPUT:
Enter name: Geetha
Hello Geetha

9|P age
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK-3: Loops and conditionals
IF Statement
The if statement is used to check a condition.
If the condition is true, Python executes the block of code under it.
Syntax
if condition:
# code to run when condition is true

ELIF Statement (else if)


elif is used when you want to check another condition
but only if the previous if condition was false.
Syntax
elif another_condition:
# code to run when this condition is true

ELSE Statement
else is used when none of the previous conditions are true.
It acts as a final fallback.

Syntax
else:
# code to run when all conditions above are false

Full Syntax Together

if condition1:
# code
elif condition2:
# code
elif condition3:
# code
else:
# code

Loops:
Loops let you run the same block of code many times.
Python has two main loops:

10 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
1. for loop
 Used to repeat code for each item in something (like a list, string, or range).
 It uses the keyword in to go through items one by one.
 Syntax:

for variable in sequence:


# code

2. while loop
 Repeats code as long as a condition is true.
 Syntax:

while condition:
# code

What is range?
range() is a built-in function that creates a sequence of numbers.
It is often used in for loops when you want to repeat something a specific number of times.
range(stop)
range(start, stop)
range(start, stop, step)
Example idea (not code): “Repeat 5 times” → use range(5)

Use of the keyword in


The keyword in tells the loop to go through each item in a sequence.
It means, taking each element from this list/string/range one by one.

(A). AIM: Write a program to print the following patterns using loop:
*
**
***
****

SOURCE CODE:
n = int(input("Rows: "))
for i in range(1, n+1):
print("*" * i)

OUTPUT:
Rows: 4
*
**
***
****

11 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
(B). AIM: Write a program to print multiplication table of a given number X1 to
range X2.

SOURCE CODE:

x1 = int(input("Number: "))
x2 = int(input("Range: "))
for i in range(1, x2+1):
print(x1, "x", i, "=", x1*i)

OUTPUT:

Number: 5
Range: 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25

12 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 4: Strings
Strings:

Strings in python are surrounded by either single quotation marks, or double quotation marks.
Example: print (“hello”) (or) print(‘hello’)
Assign String to a variable: Assigning a string to a variable is done with the variable name
followed by an equal sign and the string.
Example: a=”hello”
print(a)

Multiline Strings: We can assign a multiline string to a variable by using either three double
quotes or three single quotes. Strings in python are treated as an array of characters. We can
access the characters of the string with the help of index value, where the first character of the
string has the index value is zero.

Example: a=”hello”
print(a[1]) # prints the character ‘e’

Looping through a string: We can loop through the characters in a string, using for loop.

Example: a=”gvpcoe”
for x in a:
print(x)

Slicing Strings: We can return a range of characters by using the slice syntax. Specify the
start index and the end index, separated by a colon, to return a part of the string.

Example: a=”gvpcoe”
print(a[3:6]) # prints “coe”
Example: a=”gvpcoe”
print(a[:3]) # prints “gvp”
Example: a=”gvpcoe”
print(a[3:]) # prints “coe”

String Methods:

1) len():To get the length of a string, use the len() function.

Example: a=”gvpcoe”

print(len(a)) # prints the value “6”

2) upper():This method returns the string in uppercase.

13 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
Example: a=”gvpcoe”

print([Link]()) # prints “GVPCOE”

3) lower():This method returns the string in lowercase.

Example: a=”GvpCoe”

print([Link]()) #prints “gvpcoe”

4) strip():This method removes any whitespace from the beginning or the end.

5) replace(): This method replaces a string with another string.

Example: a=”gvpcoe”

print([Link](“g”,”G”)) # prints “Gvpcoe”

6) split():This method returns a list where the text between the specified separator becomes
the list items.

Example: a=”gvp,college,of,engineering”

b=[Link](“,”)

print(b) # prints [“gvp”,”college”,”of”,”engineering”]

7) index(): This method finds the index of the first occurrence of the specified value. If the
value is not found, it will raise an exception.

Example: a=”hello”

print([Link](“l”)) #prints “2”

Note:find() and index() method are almost same, but the only difference is that the find()
returns -1 if the value is not found.

(A). AIM: Write a program to find the length of the string without using any
library functions.

SOURCE CODE:

s = input("Enter string: ")


count = 0
for ch in s:
count += 1
print("Length:", count)

14 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
OUTPUT:
Enter string: hello
Length: 5

(B). AIM: Write a program to check if two strings are anagrams or not.

SOURCE CODE:

a = input("First: ")
b = input("Second: ")
print("Anagram?", sorted(a) == sorted(b))

OUTPUT:
First: listen
Second: silent
Anagram? True

(C). AIM: Write a program to check if the substring is present in a given string
or not.

SOURCE CODE:

s = input("String: ")
sub = input("Substring: ")
print("Found?", sub in s)

OUTPUT:
String: hello world
Substring: world
Found? True

15 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 5: LISTS
Lists are used to store multiple items in a single variable.
Creation of list: Lists are created using square brackets.
Example:l1=[“cse”,”eee”,”ece”]
print(l1)
In the above example cse,ece,eee are called as items.
Note: List items are ordered, changeable, and allow duplicate values. List items are indexed
and can be of any data type.

List length: To determine how many items a list has, use the len() function.
Example:a=[10,”ram”,88.50]
print(len(a)) # prints 3
type():Data type of a list is <class ‘list’>
Example:print(type(a))
list():We can also create a new list by using list() constructor.
Example:a=list((10,”ram”,88.50))

Access List Items: List items are indexed and you can access them by referring to the index
number.
Example: a=[“apple”,”banana”,”orange”]
print(a[1]) # prints “banana”

Looping through Lists:


1) Using for loop:
Example:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

2) Using index numbers: Use the range() and len() functions to create a suitable iterable.
Example:thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])

3) Using a while loop:


Example:
thislist = ["apple", "banana", "cherry"]
i=0
while i <len(thislist):
print(thislist[i])

16 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
i=i+1

Sort Lists: List objects have a sort method that will sort the list alphanumerically, ascending,
by default.
Example:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(thislist)

(A). AIM: Write a program to perform the given operations on a list: i. add ii.
insert iii. Slicing

SOURCE CODE:

lst = list(map(int, input().split()))


[Link](int(input("Add: ")))
[Link](1, int(input("Insert: ")))
print(lst, lst[1:4])

OUTPUT:

123
Add: 4
Insert: 10
[1, 10, 2, 3, 4] [10, 2, 3]

(B). AIM: Write a program to perform any 5 built-in functions by taking any list.

SOURCE CODE:

list1=[]
n1=int(input())#[Link] elements you want to add in list1
#Enter the elements of the list1
for i in range(0,n1):
ele=int(input())
[Link](ele)
c=int(input())#Enter the element you want to count in the list
print("List is “+str(list1))
print("Length of list is “+ str(len(list1)))
print("Sum of list is “+str(sum(list1)))
print("Max of list is ”+str(max(list1)))
print("Min of list is “+str(min(list1)))

17 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
print("Count of “+str(c)+” in list is “+str([Link](c)))
OUTPUT:
5
10 20 30 40 20
20
List is [10, 20, 30, 40, 20]
Length of list is 5
Sum of list is 120
Max of list is 40
Min of list is 10
Count of 20 in list is 2

(C). AIM: Write a program to get a list of the even numbers from a given list of
numbers. (use only comprehensions)

SOURCE CODE:

lst = list(map(int, input().split()))


evens = [x for x in lst if x % 2 == 0]
print(evens)

OUTPUT:
123456
[2, 4, 6]

18 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 6: TUPLES
Tuples:
Tuples are used to store multiple items in a single variable. A tuple is a collection which is
ordered and unchangeable.
Ex:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
('apple', 'banana', 'cherry')

Tuple items are ordered, unchangeable, and allow duplicate values.


Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
('apple', 'banana', 'cherry', 'apple', 'cherry')

Tuple Length:
To determine how many items a tuple has, use the len() function:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
3

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
('apple', 'banana', 'cherry')

Access Tuple Items


You can access tuple items by referring to the index number, inside square brackets:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
banana

Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
cherry

19 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
(A). AIM: Write a program to create tuples (name, age, address, college) for at
least two members and concatenate the tuples and print the concatenated tuples.

SOURCE CODE:

t1 = tuple(input().split())
t2 = tuple(input().split())
print(t1 + t2)

OUTPUT:
A 20 City1 Col1
B 22 City2 Col2
('A', '20', 'City1', 'Col1', 'B', '22', 'City2', 'Col2')

(B). AIM: Write a program to return the top 'n' most frequently occurring chars
and their respective counts. e.g. aaaaabbbbcccc, 2 should return [(a 5) (b 4)]

SOURCE CODE:

s = input()
n = int(input())
freq = {c: [Link](c) for c in set(s)}
print(sorted([Link](), key=lambda x: -x[1])[:n])

OUTPUT:
aaaabbbbccc
2
[('a', 4), ('b', 4)]

20 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 7: SETS
Sets:
Sets are used to store multiple items in a single [Link] items are unordered,
unchangeable, and do not allow duplicate values.
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
{'apple', 'banana', 'cherry'}
Set items can be of any data type
set1 = {"abc", 34, True, 40, "male"}
sets are defined as objects with the data type 'set'
print(type(set1))
<class 'set'>

set() Constructor
Set can also be created using the set() constructor
thisset = set(("apple", "banana", "cherry")) # Use double round-brackets
print(thisset)
{'apple', 'banana', 'cherry'}

Access Items
set items can be accessed using a for loop,it can be checked if a specified value is present in a
set, by using the in keyword.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
apple
banana
cherry
print("bananas" in thisset)
False

Change Items
Once a set is created, you cannot change its items, but you can add new items.

Add Items
To add one item to a set use the add() method.
To add items from another set into the current set, use the update() method.
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)

21 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
{'cherry', 'apple', 'orange', 'banana'}

Remove Item
To remove an item in a set, use the remove(), or the discard() method
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
If the item to remove does not exist, remove( ) will raise an error, but discard() will not raise
an error.
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)

pop() method to remove the last item. Since sets are unordered,you will not know what item
that gets removed.
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
print(thisset)
apple
{'banana', 'cherry'}

clear() method empties the set


thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
set()
del keyword will delete the set completely
thisset = {"apple", "banana", "cherry"}
delthisset

(A). AIM: Write a program to count the number of vowels in a string (No control
flow allowed).

SOURCE CODE:

vowels = "aeiouAEIOU"
s = input("Enter a string: ")
count = sum([1 for i in s if i in vowels])
print("The number of vowels in "+s+" is "+str(count))

22 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
OUTPUT:
Enter a string: gayatri college
The number of vowels in gayatri college is 6

(B). AIM: Write a program that displays which letters are present in both
strings.

SOURCE CODE:

s1 = input("Enter string1: ")


s2 = input("Enter string2: ")
common = set(s1).intersection(set(s2))
print(f"Common letters for above strings : {common}")

OUTPUT:
Enter string1: lemon
Enter string2: orange
Common letters for above strings : {'e', 'o', 'n'}

(C). AIM: Write a program to sort given list of strings in the order of their vowel
counts.

SOURCE CODE:

vowels = "aeiouAEIOU"
def vowelcount(x):
p = sum([1 for i in x if i in vowels])
return p
s = input("Enter multiple strings :").split()
print(sorted(s,key=vowelcount, reverse=True))

OUTPUT:
Enter multiple strings :this is best engineering college
['engineering', 'college', 'this', 'is', 'best']

23 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 8: DICTIONARIES
What is a Dictionaries?
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is unordered, changeable and does not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Example:
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items:
Dictionary items are unordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Unordered
When we say that dictionaries are unordered, it means that the items does not have a defined
order, you cannot refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:

Dictionary Length:
To determine how many items a dictionary has, use the len() function:
Example:
Print the number of items in the dictionary:
print(len(thisdict))

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
Example:
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,

24 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
"year": 1964,
"colors": ["red", "white", "blue"]
}

Check if Key Exists:


To determine if a specified key is present in a dictionary use the in keyword:
Example:
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Change Values:
You can change the value of a specific item by referring to its key name:
Example:
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Update Dictionary:
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example:
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})

Adding Items:
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example:

25 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Update Dictionary:
The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example:
Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"color": "red"})

Removing Items:
There are several methods to remove items from a dictionary:
Example:
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)

26 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
(A). AIM: Write a program to check if a given key exists in a dictionary or not.

SOURCE CODE:

d ={1:10,2:20,3:30,4:40,5:50,6:60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)

OUTPUT:
Key is present in the dictionary
Key is not present in the dictionary

(B). AIM: Write a program to add a new key-value pair to an existing dictionary.

SOURCE CODE:

CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1}


print(CountryCodeDict)
CountryCodeDict["Spain"]= 34
print "After adding"
print(CountryCodeDict)

OUTPUT:
{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}

(C). AIM: Write a program to sum all the items in a given dictionary.

SOURCE CODE:

my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))

OUTPUT:
293

27 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 9: FILES
Files

Handling files in python


Data is often stored in text files, which is organized. There are many kinds of files. Text files,
music files, videos, and various word processor and presentation documents are those we are
familiar with. Text files only contain characters whereas, all the other file formats include
formatting information that is specific to that file format. Operations performed on the data in
files include the read and write operations. To perform any operation the program must open
the file. The syntax to open a file is given below:
with open(«filename», «mode») as «variable»:
«block»

Reading a file:
There are several techniques for reading files. One way is reading the overall contents of the
file into a string and we also have iterative techniques in which in each iteration one line of
text is read. We, can also read each line of text and store them all in a list. The syntax for
each technique is given below
#to read the entire contents of text into a single string
with open('[Link]', 'r') as f:
contents = [Link]()
#to read each line and store them as list
with open('[Link]', 'r') as f:
lines = [Link]()
#for iterative method of reading text in files
with open('[Link]', 'r') as f:
for line in f:
print(len(line))

(A). AIM: Write a program to sort words in a file and put them in another file.
The output file should have only lower-case words, so any upper case words from
source must be lowered.

SOURCE CODE:

ipfile = open("[Link]",'r')
l = [Link]().split("\n")
lt = []
for i in l:
for j in [Link]():
[Link]([Link]())
[Link]()

28 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
print(lt)
opfile = open("[Link]", "w")
for i in lt:
[Link](str(i)+"\n")
[Link]()
[Link]()

OUTPUT:
['feel', 'great', 'hail', 'hello', 'i', 'is', 'is', 'lab', 'manual', 'python', 'python', 'python', 'this']

(B). AIM: Write a program to find the most frequent words in a text. (read from
a text file).

SOURCE CODE:

defword_freq(s):
dic ={}
keys = [Link]()
for n in s:
if n in keys:
dic[n] += 1
else:
dic[n] = 1
return dic
ipfile = open("[Link]",'r')
l = [Link]().split("\n")
lt = []
for i in l:
for j in [Link]():
[Link]([Link]())
cf = word_freq(lt)
n = max(list([Link]()))
print("Most frequently occuring words and it's frequency")
forkey,val in [Link]():
ifval>=n:
print(key,val)

OUTPUT:
Most frequently occurring words and it's frequency
python 16

29 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 10: CLASSES
What are classes and objects?
A class is a code template for creating objects. Objects have member variables and have
behaviour associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the
instance of the class. In Python we create instances in the following manner.
class_instance = class_name(*arguments)
How to create classes ?
The simplest class can be created using the class keyword. For example, let's create a simple,
empty class with no functionalities.
>>> class Snake:
>>> pass
>>> snake = Snake()
>>> print(snake)
<<< main .Snake object at 0x7f315c573550>

Attributes and Methods in class: A class by itself is of no use unless there is some
functionality associated with it. Functionalities are defined by setting attributes, which act as
containers for data and functions related to those attributes. Those functions are called
methods.

● Attributes: You can define the following class with the name Snake. This class will have
an attribute name.
>>> class Snake:
... name = "python"
... # set an attribute `name` of the class
You can assign the class to a variable. This is called object instantiation. You will then be
able to access the attributes that are present inside the class using the dot . operator. For
example, in the Snake example, you can access the attribute name of the class Snake.
>>> # instantiate the class Snake and assign it to variable snake
>>> snake = Snake()
>>> # access the class attribute name inside the class Snake.
>>> print([Link])
<<< python

● Methods: Once there are attributes that “belong” to the class, you can define functions that
will access the class attribute. These functions are called methods. When you define
methods, you will need to always provide the first argument to the method with a self
keyword. For example, you can define a class Snake, which has one attribute name and one
method change_name. The method change name will take in an argument new_name

30 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
along with the keyword self.
>>> class Snake:
... name = "python"
... def change_name(self, new_name):
... [Link] = new_name
... # access the class attribute with the self keyword
... # Note: first argument of method is self
Now, you can instantiate this class Snake with a variable snake and then change the name
within the method change_name.
>>> # instantiate the class
>>> snake = Snake()
>>> # print the current object name
>>> print([Link])
<<< python
>>> # change the name using the change_name method
>>> snake.change_name("anaconda")
>>> print([Link])
<<< anaconda

● Instance attributes in python and the init method: You can also provide the values for
the attributes at runtime. This is done by defining the attributes inside the init method.
The following example illustrates this.
class Snake:
def init (self, name):
[Link] = name
def change_name(self, new_name):
[Link] = new_name
Now you can directly define separate attribute values for separate objects. For example,
>>> # two variables are instantiated
>>> python = Snake("python")
>>> anaconda = Snake("anaconda")
>>> # print the names of the two variables
>>> print([Link])
<<< python
>>> print([Link])
<<< anaconda

(A). AIM: Write a Python class named Person with attributes name, age, weight
(kgs), height (ft) and takes them through the constructor and exposes a method
get_bmi_result() which returns one of "underweight", "healthy", "obese".

31 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
SOURCE CODE:

class person(object):
def init (self, name, age, height, weight):
[Link] = name
[Link] = age
[Link] = height
[Link] = weight
def get_bmi(self):
bmi = float([Link] / (([Link] * 0.3048) ** 2))
return 'Underweight' if (bmi < 18.5) else 'Healthy' if (bmi >= 18.5 and bmi < 25) else
'Obese'
# Above line includes ternary operator in python
p1 = person('Person 1', 25, 6, 30)
print([Link], 'is', p1.get_bmi())
p2 = person('Person 2', 25, 6, 200)
print([Link], 'is', p2.get_bmi()

OUTPUT:
Person 1 is Underweight
Person 2 is Obese

(B). AIM: Write a Python class named Circle constructed by a radius and two
methods which will compute the area and the perimeter of a circle.

SOURCE CODE:

class Circle():
def init (self, r):
[Link] = r
def area(self):
return 3.14 * ([Link]**2)
def perimeter(self):
return 2 * 3.14 * [Link]
radius = int(input('Enter radius of circle: '))
circle = Circle(radius)
print(f'Area of circle is {[Link]()}')
print(f'Perimeter of circle is {[Link]()}')

OUTPUT:
Enter radius of circle: 7
Area of circle is 153.86
Perimeter of circle is 43.96

32 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 11: ARRAYS
Python Arrays :
Python does not have built-in support for Arrays, but Python Lists can be used instead.

Arrays:
Note: We use LISTS as ARRAYS, however, to work with arrays in Python you will have to
import a library, like the NumPy library. Arrays are used to store multiple values in one
single variable:
# Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables
could look like this.
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
# using array
cars = ["Ford", "Volvo", "BMW"]
However, what if you want to loop through the cars and find a specific one? And what if you
had not 3 cars, but 300? The solution is an array, An Array can hold many values under a
single name, and you can access the values by referring to an index number.

Access the Elements of an Array


You refer to an array element by referring to the index number.
# Get the value of the first array item:
x = cars[0]
# Modify the value of the first array item:
cars[0] = "Toyota"

The Length of an Array


Use the len() method to return the length of an array. (No. of elements in an array)
x = len(cars) # number of elements in the cars array
Note: The length of an array is always one more than the highest array index.
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
for x in cars:
print(x)

33 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
Adding Array Elements
You can use the append() method to add an element to an array.
# Add one more element to the cars array:
[Link]("Honda")

Removing Array Elements


You can use the pop() method to remove an element from the array.
#Delete the second element of the cars array:
[Link](1)
# You can also use the remove() method
# to remove an element from the array.
#Delete the element that has the value "Volvo":
[Link]("Volvo")
Note: The list's remove() method only removes the first occurrence of the specified value.

Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
1. append(): Adds an element at the end of the list
2. clear(): Removes all the elements from the list
3. copy(): Returns a copy of the list
4. count(): Returns the number of elements with the specified value
5. extend(): Add the elements of a list (or any iterable), to the end of the current list
6. index(): Returns the index of the first element with the specified value
7. insert(): Adds an element at the specified position
8. pop(): Removes the element at the specified position
9. remove(): Removes the first item with the specified value
10. reverse(): Reverses the order of the list
11. sort(): Sorts the list

(A). AIM: Write a program to create, display, append, insert and reverse the
order of the items in the array.

SOURCE CODE:

# Create array
array = [1, 2, 3, 4, 5]
# display array
print(f'Created Array : {array}')
# Append 6,7 to array
[Link](6)
[Link](7)
print(f'Array after appending is {array}')

34 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
# Insert -1,0 at 0,1 places in array
[Link](0, -1)
[Link](1, 0)
print(f'Array after inserting is {array}')
# reverse the array
[Link]()
print(f'Array after reversing is {array}')

OUTPUT:

Created Array : [1, 2, 3, 4, 5]


Array after appending is [1, 2, 3, 4, 5, 6, 7]
Array after inserting is [-1, 0, 1, 2, 3, 4, 5, 6, 7]
Array after reversing is [7, 6, 5, 4, 3, 2, 1, 0, -1]

(B). AIM: Write a program to add, transpose and multiply two matrices.

SOURCE CODE:

import numpy as np
# Example matrices
A = [Link]([[1, 2, 3], [4, 5, 6]])
B = [Link]([[7, 8, 9], [10, 11, 12]])
# Matrix Addition
print("Matrix A:")
print(A)
print("\nMatrix B:")
print(B)
print("\nAddition of A and B:")
print(A + B)
# Transpose of A
print("\nTranspose of A:")
print(A.T)
# For multiplication, shape of A and B2 must be compatible
B2 = [Link]([[1, 2],[3, 4],[5, 6]])
print("\nMatrix B2:")
print(B2)
# Matrix Multiplication (A x B2)
print("\nMultiplication of A and B2:")
print([Link](A, B2))

35 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
OUTPUT:
Matrix A:
[[1 2 3]
[4 5 6]]

Matrix B:
[[ 7 8 9]
[10 11 12]]

Addition of A and B:
[[ 8 10 12]
[14 16 18]]

Transpose of A:
[[1 4]
[2 5]
[3 6]]

Matrix B2:
[[1 2]
[3 4]
[5 6]]

Multiplication of A and B2:


[[22 28]
[49 64]]

36 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
WEEK 12: PYTHON MAPS ,FILTERS
&GENERATORS
1. map() Function
The map() function in Python is used to apply a specific function to every element of an
iterable such as a list, tuple, or set. Instead of processing each element using a loop, map()
automatically sends each item of the iterable to the given function and collects the processed
results. It does not return a list directly; instead, it returns a map object, which is an iterator.
This means the values are generated only when needed, making it efficient for large datasets.
Syntax
map(function, iterable)

2. filter() Function
The filter() function is used to select elements from an iterable based on a condition. It takes a
function that returns either True or False, and applies this function to every element of the
iterable. Only those elements for which the function returns True are kept in the result. Like
map(), the filter() function also returns an iterator (a filter object) instead of a list.
Syntax
filter(function, iterable)

3. Generators
Generators in Python are special functions that allow you to generate a sequence of values
one at a time, instead of creating and storing the entire sequence in memory. They are defined
like normal functions but use the yield keyword instead of return. Each time a generator’s
next() method is called, execution resumes from where it last paused, producing the next
value. Because they produce values lazily (on demand), generators are memory-efficient and
suitable for working with large data or infinite sequences. Generator expressions also exist,
which look similar to list comprehensions but use parentheses instead of square brackets.

Syntax (Generator Function)


def generator_function():
yield value

Syntax (Generator Expression)


(expression for item in iterable)

37 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
(A). AIM: Accept two lists, one list represents temperatures in Fahrenheit and
another list represents temperatures in Celsius. Perform map operations
Fahrenheit-Celsius and Celsius-Fahrenheit using lambda

SOURCE CODE:

def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
t = (36.5, 37, 37.5, 38, 39)
f=list(map(fahrenheit, t))
c=list(map(celsius,f))
print(f)
print(c)
d=list(map(lambda x: (float(9)/5)*x + 32, t))
e=list(map(lambda x: (float(5)/9)*(x - 32), f))
print(d)
print(e)

OUTPUT:
[97.7 ,98.60000000000001 , 99.5, 100.4, 102.2]
[36.5, 37.0000000000001, 37.5, 38.0000000000001, 39.0]

(B). AIM: Create a Fibonacci sequence that contains ‘N’ terms, and filter only
even terms using lambda

SOURCE CODE:

from functools import reduce


fib_series = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]], range(n-2), [0, 1])
print(fib_series(6))

OUTPUT:
[0, 1, 1, 2, 3, 5]

38 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)
(C). AIM: Write a program to find the number of rows in a text file using
Generator and yield.

SOURCE CODE:

def csv_reader(file_name):
file = open(file_name)
result = [Link]().split("\n")
return result
csv_gen = csv_reader("[Link]")
row_count = 0
for row in csv_gen:
row_count += 1
print(f"Row count is {row_count}")

(D). AIM: Find Sum of Squares of 1 to n numbers using Generator Expressions.

SOURCE CODE:

my_list = [1, 3, 6, 10]


list= [x**2 for x in my_list]
print(list)
print(sum(list))

OUTPUT:
[1, 9, 36, 100]
146

39 | P a g e
Gayatri Vidya Parishad College of Engineering (Autonomous)

You might also like