Python Programming (2180711)
Semester-VIII
SET-1
Data Types, Operators
1. (a) Demonstrate the use of id(), type() and size() function in python.
Program:-
str1 = "geek"
print(id(str1))
str2 = "geek"
print(id(str2))
# This will return True
print(id(str1) == id(str2))
# Use in Lists
list1 = ["aakash", "priya", "abdul"]
print(id(list1[0]))
print(id(list1[2]))
# This returns false
print(id(list1[0])==id(list1[2]))
Output:-
1. (b) Write a program to perform basic operations in python.
Program:-
# Examples of Arithmetic Operator
a=9
b=4
Enrollment Number:150953107008 Page 1
Python Programming (2180711)
Semester-VIII
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
Output:-
Enrollment Number:150953107008 Page 2
Python Programming (2180711)
Semester-VIII
Theory:
The id() function returns identity (unique integer) of an object.
The syntax of id() is:
id(object)
As we can see the function accepts a single parameter and is used to return the identity of an
object. This identity has to be unique and constant for this object during the lifetime. Two objects
with non-overlapping lifetimes may have the same id() value. If we relate this to C, then they are
actually the memory address, here in Python it is the unique id. This function is generally used
internally in Python.
Examples:
The output is the identity of the object passed. This is random but when running in the same
program, it generates unique and same identity.
Input : id(1025)
Output : 140365829447504
Output varies with different runs
Input : id("geek")
Output : 139793848214784
The type() Function:-
Python have a built-in method called as type which generally come in handy while figuring out
the type of variable used in the program in the runtime. The type function returns the datatype of
any arbitrary object. The possible types are listed in the types module. This is useful for helper
functions that can handle several types of data.
Example : Introducing type
Input: type(1)
Enrollment Number:150953107008 Page 3
Python Programming (2180711)
Semester-VIII
Output: <type <int>>
Input: L=[23,34,45]
type(li)
Output: <type <list>>
Enrollment Number:150953107008 Page 4
Python Programming (2180711)
Semester-VIII
SET-2
Control Statements and Iteration
2. (a) Write a Python program to find all prime numbers within a given range.
Program:-
#Take the input from the user:
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Output:-
Enrollment Number:150953107008 Page 5
Python Programming (2180711)
Semester-VIII
2. (b) Write a Python program to print ‘n terms of Fibonacci series using iteration.
Program:-
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Enrollment Number:150953107008 Page 6
Python Programming (2180711)
Semester-VIII
Output:-
Enrollment Number:150953107008 Page 7
Python Programming (2180711)
Semester-VIII
SET-3
String
3.(a) Write a program for various function of string in python.
Program:-
String1 = 'Welcome to the I.T.M'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a I.T.M"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a I.T.M and I live in a world of "I.T.M"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
# Creating String with triple
# Quotes allows multiple lines
Enrollment Number:150953107008 Page 8
Python Programming (2180711)
Semester-VIII
String1 = '''I.T.M
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:-
3.(b) To add 'ing' at the end of a given string (length should be at least 3). If the given string
already ends with 'ing' then add 'ly' instead. If the string length of the given string 5. is less than
3, leave it unchanged. Sample String : 'abc' Expected Result : 'abcing' Sample String : 'string'
Expected Result : 'stringly'
Program:-
def add_string(str1):
length = len(str1)
Enrollment Number:150953107008 Page 9
Python Programming (2180711)
Semester-VIII
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))
Output:-
Function of String in Python:
Method Description
capitalize() Converts the first character to upper case
Enrollment Number:150953107008 Page 10
Python Programming (2180711)
Semester-VIII
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it
was found
index() Searches the string for a specified value and returns the position of where it
was found
isdigit() Returns True if all characters in the string are digits
isidentifier( Returns True if the string is an identifier
)
islower() Returns True if all characters in the string are lower case
Enrollment Number:150953107008 Page 11
Python Programming (2180711)
Semester-VIII
isupper() Returns True if all characters in the string are upper case
lower() Converts a string into lower case
replace() Returns a string where a specified value is replaced with a specified value
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Enrollment Number:150953107008 Page 12
Python Programming (2180711)
Semester-VIII
SET-4
List,Tuple and Dictionary
4.(a) Write a program for list and its various in-built methods.
Program:-
# Adds List Element as value of List.
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)
List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2,10087)
print(List)
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1)
#Add List1 to List2 now
List2.extend(List1)
print(List2)
Enrollment Number:150953107008 Page 13
Python Programming (2180711)
Semester-VIII
List = [1, 2, 3, 4, 5]
print(sum(List))
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(min(List))
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(max(List))
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
#Reverse flag is set True
List.sort(reverse=True)
#List.sort().reverse(), reverses the sorted list
print(List)
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop())
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
del List[0]
print(List)
Enrollment Number:150953107008 Page 14
Python Programming (2180711)
Semester-VIII
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
List.remove(3)
print(List)
Output:-
4.(b) Write a program to calculate the sum of numbers stored in a list.
Program:-
# Python program to find sum of elements in list
total = 0
# creating a list
list1 = [11, 3, 17, 9, 15, 33]
# Iterate each element in list
# and add them in variale total
for ele in range(0, len(list1)):
total = total + list1[ele]
Enrollment Number:150953107008 Page 15
Python Programming (2180711)
Semester-VIII
# printing total value
print("Sum of all elements in given list: ", total)
Output:-
4.(c) Write a program for tuple and its various in-built methods.
Program:-
# the use of tuple() function
# when parameter is not passed
tuple1 = tuple()
print(tuple1)
# when an iterable(e.g., list) is passed
list1= [ 1, 2, 3, 4 ]
tuple2 = tuple(list1)
print(tuple2)
# when an iterable(e.g., dictionary) is passed
dict = { 1 : 'one', 2 : 'two' }
tuple3 = tuple(dict)
print(tuple3)
# when an iterable(e.g., string) is passed
string = "geeksforgeeks"
Enrollment Number:150953107008 Page 16
Python Programming (2180711)
Semester-VIII
tuple4 = tuple(string)
print(tuple4)
Output:-
4.(d) Write a program to enter data in a dictionary and print the data in sorted order using keys as
well as using values.
Program:-
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}
for key in sorted(color_dict):
print("%s: %s" % (key, color_dict[key]))
Output:-
Enrollment Number:150953107008 Page 17
Python Programming (2180711)
Semester-VIII
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the
specified value
extend() Add the elements of a list (or any iterable), to
the end of the current list
index() Returns the index of the first element with the
specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified
value
Enrollment Number:150953107008 Page 18
Python Programming (2180711)
Semester-VIII
reverse() Reverses the order of the list
sort() Sorts the list
Dictionary in-built methods in python:
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
Enrollment Number:150953107008 Page 19
Python Programming (2180711)
Semester-VIII
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault( Returns the value of the specified key. If the key does not exist: insert the
) key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Enrollment Number:150953107008 Page 20