Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python File Mca

The document is a practical file for a Master of Computer Applications course focusing on programming concepts using Python. It includes various practical exercises demonstrating Python's data types, string manipulations, operators, list operations, and object-oriented programming concepts. Additionally, it provides an introduction to Python, its history, features, and applications.

Uploaded by

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

Python File Mca

The document is a practical file for a Master of Computer Applications course focusing on programming concepts using Python. It includes various practical exercises demonstrating Python's data types, string manipulations, operators, list operations, and object-oriented programming concepts. Additionally, it provides an introduction to Python, its history, features, and applications.

Uploaded by

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

G.B.

PANT UNIVERSITY OFAGRICULTURE & TECHNOLOGY


COLLEGE OF TECHNOLOGY
MASTER OF COMPUTER APPLICATIONS

PRACTICAL
FILE FOR
PROGRAMMING
CONCEPT USING
PYTHON MCA (606)

Submitted To - Submitted By -
Dr. Shobha Arya Nandita Roy (62755)
INDEX

S.No Name of Practical Sign

1. Program to demonstrate different number of


data types in python.
2. Program for string manipulations and python
script.
3. Program to demonstrate different operators in
python.
4. Program for list operation(creation, insertion,
deletion, append).
5. Program for creation of dictionaries in python
and their operations.
6. Program for creating functions and using
functions in different files in python
7. OOPS concepts in python.

8. Program to print pyramid pattern.

9. Program to generate the Fibonacci series.

10. Program to check whether a given number is an


Armstrong number or not.
11. Program to check whether a given number is
prime or not.
12. Program to calculate factorial of a number using
recursion.
Python

Introduction to Python :
Python is a high level, interpreted programming language that is
widely used for various purposes such as web development, data
analysis, artificial intelligence, and scientific computing.

History of Python :
Python was created by Guido Van Rossum in the late 1980s ad was
first released in 1991. It is named after the popular British comedy
show Monty Python.

Basic features of Python :

 It is simple and easy to learn language.


 Open source.
 Platform independent language.
 It has rich library.
 It is portable language.
 It is embedded and extensible language.
 Object oriented language.
 Dynamically typed language

Applications of Python :

 Web development
 Machine learning and AI
 Software development
 Network programming
 CAS applications
LAB – 1
Aim – Program to demonstrate different
number of data types in python.

Data types are the classification or categorization of data items.


It represents the kind of value that tells what operations can be
performed on a particular data.

The following are the built-in data types in Python :


 Numeric – int, float, complex.
 Sequence type – string, list, tuple.
 Mapping type – dict.
 Boolean – bool.
 Set type – set, frozenset.
 Binary types – bytes, bytearray, memoryview.

1. Numeric data type –


The numeric data type in python represents the data that
has a numeric value.
 Integers – this value is represented by int class. It
contains positive or negative whole numbers(without
fraction or decimals). Ex – (-1,0,4) etc.
 Float – this value is represented by the float class. It is
specified by a decimal point. Ex- (1.2, 3.4, 6.8) etc.
 Complex numbers – this number is represented by a
complex class.
2. Sequence data type –
The sequence data type in python is the ordered collection
of similar or different data types, it allows storing of multiple
values in an organized and efficient manner.
 String – string is a collection of one or more characters
put in a single quote, double or triple quote.
 List – lists are like arrays, declared in other languages
which is an ordered collection of data, items in lists do
not need to be of the same type.
 Tuple – tuple is also an ordered collection of objects,
tuples are immutable i.e it cannot be modified after it
is created.

Code –
a = "I am a student of MCA"
print("a is a", type(a))
b = 24
print("b is a", type(b))
c = 19.5
print("c is a", type(c))
d = 6j
print("d is a", type(d))
e = ["Guava", "Litchi", "Cherry"]
print("e is a", type(e))
f = ("Car", "Bike", "Bus")
print("f is a", type(f))
g = range(10)
print("g is a", type(g))
h = {"name": "Arnav", "age": 22}
print("h is a", type(h))
i = {"Python", "Java", "SQL"}
print("i is a", type(i))
j = frozenset({"Linux", "Windows", "Mac"})
print("j is a", type(j))
k = True
print("k is a", type(k))
l = b"GBPUAT"
print("l is a", type(l))
m = bytearray(4)
print("m is a", type(m))
n = memoryview(bytes(6))
print("n is a", type(n))
o = None
print("o is a", type(o))

Output –

a is a <class 'str'>
b is a <class 'int'>
c is a <class 'float'>
d is a <class 'complex'>
e is a <class 'list'>
f is a <class 'tuple'>
g is a <class 'range'>
h is a <class 'dict'>
i is a <class 'set'>
j is a <class 'frozenset'>
k is a <class 'bool'>
l is a <class 'bytes'>
m is a <class 'bytearray'>
n is a <class 'memoryview'>
o is a <class 'NoneType'>

=== Code Execution Successful ===


LAB – 2
Aim – Program for string manipulations and python
script.

String – a string in python is a sequence of characters enclosed in


single, double or triple quotes. These are immutable, which means
their content cannot be changed after creation.

Operations on string –

1. String concatenation – concatenation refers to combining two or


more strings using + operator.
Code –
a = "Hello"
b = "World"
result = a + " " + b
print("Concatenation :", result)
Output –
Concatenation : Hello World

=== Code Execution Successful ===


2. Repetition of string using * - the * operator repeats the string a
specified number of times.
Code –
text = "Python"
repeated = text * 3
print("Repeated string :", repeated)
Output –

Repeated string : PythonPythonPython


3. Indexing in string – indexing refers to accessing specific
characters using their position (index). Index starts at 0.
Code –
text = "Python"
print("Character at index 0 :",text[0])
print("Character at index 4 :",text[4])
Output –

Character at index 0 : P
Character at index 4 : o

4. Slicing in string – slicing extracts a substring using start:stop:step.


Code –
text = "Python Programming"
substring = text[0:6]
print("Sliced string :", substring)
Output –
Sliced string : Python

5. Checking string membership – the in keyword checks if a


substring exists in the string.
Code –
text = "Python Programming"
print("Python" in text)
print("Java" in text)
Output –
True
False
6. Length of a string – the len() function calculates the number of
characters in a string.
Code –
text = "Hello I'm a MCA student"
print("Length of the string :", len(text))
Output –
Length of the string : 23

7. Finding a substring – the find() method searches for a substring


and returns the index of its first occurrence.
Code –
text = "Python Programming"
index = text.find("Pro")
print("Index of Pro :", index)
Output –
Index of Pro : 7

8. Replacing a substring – the replace() method replaces a part of


the string with another.
Code –
text = "I love python"
new_text = text.replace("love", "enjoy")
print("Replaced String :", new_text)
Output –

Replaced String : I enjoy python


LAB – 3
Aim – Program to demonstrate different Operator
data types in python.

Operators – an operator is a character that represents a specific


mathematical or logical action or process.
Python divides the operators in seven groups –
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operator
7. Bitwise operators
Arithmetic operators – arithmetic operators are used with numeric
values to perform common mathematical operations.
Operator Description Syntax
+ Addition: adds two operands x+y
- Subtraction: subtracts two operands x– y
* Multiplication: multiplies two operands x*y
/ Division(float): divides the first operand by x/y
the second
// Divison(floor): divides the first operand by x // y
the second
% Modulus: returns the remainder when the x%y
first operand is divided by the second
** Power: returns first raised to power second x ** y
Code – Output –
x = 20
28
y=8
12
print(x+y)
2.5
print(x-y)
160
print(x/y)
2
print(x*y)
4
print(x//y)
25600000000
print(x%y)
print(x**y)
=== Code Execution Successful ===

Assignment operators – assignment operators are used to assign


values to variable.
Operator Example Same As

= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x = x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Code – Output –
x = 10 10
print(x) 13
x+=3 11
print(x) 3.6666666666666665
x-=2 3.6666666666666665
print(x) 49.29629629629629
x/=3 49.29629629629629
print(x) 49.29629629629629
x%=5
print(x)
x**=3
print(x)
x//9
print(x)
x!=3
print(x)

Comparison operators – comparison operators are used to compare


two values.
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or x >= y
equal to
<= Less than or equal to x <= y
Code – Output –
x = 10
False
y=3
True
print(x==y)
True
print(x!=y)
False
print(x>=y)
True
print(x<=y)
False
print(x>y)
print(x<y)

Logical operators – logical operators are used to combine conditional


statement.
Operator Description Example
and Returns true if both the x < 5 and x < 10
statements are true
or Returns true if one of the x < 5 or x < 4
statement is true
not Reverse the result, returns false if not(x < 5 and x < 10)
the result is true

Code – Output –
x = True False
y = False True
print(x and y) False
print(x or y) True
print(not x )
print(not y)
Identity operators – identity operators are used to compare the
objects, not if they are equal, but if they are actually the same object,
with the same memory location.
Operator Description Example
is Returns true if both variables are the x is y
same object
is not Returns true if both variables are not x is not y
the same objcet

Code – Output –
x = [1,2,3] False
y = [1,2,3] True
print(x is y)
print(x is not y)

Membership operators – membership operators are used to test if a


sequence is present in an object.
Operator Description Example
in Returns true if a sequence with the x in y
specified value is present in the object
not in Returns true if the sequence with the x not in y
specified value is not present in the
object

Code – Output –
x = [5,6,7,8,9]
True
print(5 in x)
False
print(2 in x)
Bitwise operators – bitwise operators are used to compare (binary)
numbers.
Operator Name Description Example

& AND Sets each bit to 1 if both bits x&y


are 1
| OR Sets each bit to 1 if one of x|y
two bits is 1
^ XOR Sets each bit to 1 if and only x^y
if one of two bits is 1
~ NOT Inverts all the bits ~x
<< Zero fill Shift left by pushing zeros in x << 2
left shift form the right and let the
leftmost bits fall off
>> Signed Shift right by pushing copies x >> 2
right shift of thr leftmost bit in from the
left, and let the rightmost bits
fall off

Code – Output –
x=6 4
y=4 6
print(x&y) 2
print(x|y) -7
print(x^y) 12
print(~x) 24
print(x<<1) 3
print(x<<2) 0
print(x>>1)
print(x>>3)
LAB – 4
Aim – Program for List Operation (Creation, Insertion,
Deletion, Append)

List – list is a collection of things, enclose in [] and separated by


commas.List is a flexible, versatile, powerful and popular built – in
data type .It allows you to create variable –length and mutable
sequence of object.
List operations –
Creation of list – lists can be created by assigning elements to a
variable.
Code – Output –
my_list = [10,20,30,40] Created list : [10, 20, 30, 40]
print("Created list :", my_list)

Insertion in list – we can insert elements in list after creating a list by


insert() method at a specified index.
Code – Output –
x = [1,2,5,4] [9, 1, 2, 5, 4]
x.insert(0,9)
print(x)

Deletion from a list – elements can be removed using the pop() by


index or remove() by value methods.
Code – Output –
fruits = ['apple', 'banana', 'cherry'] ['apple', 'cherry']
fruits.pop(1)
print(fruits)

Append – the append() function in python takes a single item as


input and adds it to the end of the given list.
Code – Output –
list = [10,20,"Aaru", 10]
[10, 20, 'Aaru', 10, 'Gudiya']
list.append("Gudiya")
print(list)

Indexing in list – indexing refers to the process of acessing a specific


element in a sequence using its position or index number.Indexing in
Python starts with 0.
Code – Output –
y = [10,12.5,"Raja"] 12.5
print(y[1]) 1
print(y.index(12.5))

Slicing in list – the slice() function returns a slice object. A slice object
is used to specify how to slice a sequence using index.
Code – Output –
list = [10,20,3,50,45,25,15] [10, 20, 3, 50, 45, 25, 15]
list[1:4]
print(list)
Count – the count() method returns the number of times the
specified element appears in the list.
Code – Output –
fruits = ["apple", "banana", "cherry"] 1
x = fruits.count("cherry")
print(x)

Sorting – this method is used to sort the elements of the same data
type in ascending or descending.
Code – Output –
list = [10,20,3,5,4,5,7,9] [3, 4, 5, 5, 7, 9, 10, 20]
list.sort()
print(list)

Code – Output –
list = [10,20,3,5,4,5,7,9]
[20, 10, 9, 7, 5, 5, 4, 3]
list.sort(reverse= True)
print(list)
LAB – 5
Aim – Program for creation of dictionaries in python
and their operations.
Dictionary – dictionary are used to store data values in key value
pairs. A dictionary is a collection which is ordered, changeable and do
not allow duplicates. Dictionaries cannot have two items with the
same key. Dictionaries are written with the curly brackets, and have
keys and values.
Dictionary operations –

Creating a dictionary – we can create a dictionary by placing key-


value pairs inside curly braces {}.
Code –
dict = {"Name": "Arnav", "Age": 22, "City": "Banaras"}
print("Created dictionary :", dict)

Output –

Created dictionary : {'Name': 'Arnav', 'Age': 22, 'City':


'Banaras'}

Accessing values – we can access dictionary values using their keys.


Code – Output –
dict = {"Name": "Arnav", "Age": 22, "City": "Banaras"} Name : Arnav
print("Name :", dict["Name"])
Pop – python dictionary pop() method removes and returns the
specified element from the dictionary.
Code – Output –
n = {1:"Apple", 2:"Litchi", 3:"Grapes"} {1: 'Apple', 3: 'Grapes'}
n.pop(2)
print(n)

Get – the get() method will return the value of a dictionary entry for
a specified key.
Code – Output –
car = { Mustang
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("model")
print(x)

Clear – it will clear all the items from the dictionary.


Code – Output –
car = {
{}
"brand": "Ford",
"model": "Mustang",
"year": 1964 }
car.clear()
print(car)
Length – it will show the length of the elements in the dictionary.
Code – Output –
d ={'Name':'Steve', 'Age':30} 2
print(len(d))

Update – the update() method inserts the specified items to the


dictionary.
Code – Output –
car = {
{'brand': 'Ford', 'model': 'Mustang',
"brand": "Ford", 'year': 1964, 'color': 'White'}
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)

Delete – to delete a specific key value pair of dictionary.


Code – Output –
thisdict = {
{'brand': 'Ford', 'year': 1964}
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
LAB – 6
Aim – Program for creating functions and using
functions in different files in python.
Functions –
 Functions are block of reusable codes that perform a
specific task.
 It executes when it is called by it’s name.
 We can call a function again and again.
 The most important feature of function is code
reusability.

Types of functions in python –


1. Built-in function
2. User-defined function
3. Recursive function
4. Lambda function

Built-in functions – built-in functions are the functions whose


functionality is pre-defined in python.
Min() , max() , len() ,sum() , type() , range() , dict() , list() , tuple() ,
set() ,print() etc.
abs() function – the python abs function is used to return the
absolute value of a number.
Code – Output –
num = -7.25 -7.25
abs(num)
print(num)
all() function – it accepts an iterable object(list,dictionary etc).It
returns true if all items in passes iterable true otherwise false.
Code – Output –
mylist = [0, 1, 2] False
x = all(mylist)
print(x)

Bin() function – it is used to return the binary representation of a


specifies integer.
Code – Output –
x = bin(36) 0b100100
print(x)

Bool() function – it is used to convert a value of Boolean(true or


false) using the standard truth testing procedure.
Code – Output –
b=1
True
x = bool(b)
print(x)

Compile – it takes souce code as input and returns a code object


which can be later executed by exec() function.
Code – Output –
x = compile('print(55)', 'test', 'eval')
55
exec(x)
User-defined function – user defined function is function which is
created by the user.
Python arguments – there are following arguments in python:
 Default argument
 Keyword argument
 Positional argument
 Arbitrary argument(*args) and keyword arbitrary
argument(**kwargs)

Default argument – it is a parameter that assumes a default value if a


value is not provided in the function call for that argument.
Code – Output –
def fun(x,y=100): x: 50
print("x: ",x) y: 100
print("y: ",y)
fun(50)

Keyword argument – it allow the user to specify the argument name


with values so that the caller does not need to remember the order
of parameter.
Code – Output –
def my_function(child3, child2, child1): The youngest child is
print("The youngest child is " + child3) Linus

my_function(child1 = "Emil", child2 = "Tobias",


child3 = "Linus")
Positional argument – we can use the positional arguments during
the function call according to the position of parameters in function.
If you forget the positions, the values can be used in the wrong
places.
Code – Output –
def ad(a,b,c): 12
print(a+b+c)
ad(3,4,5)

Pass by reference or pass by value – when we pass a variable to a


function, a new reference to the object is created.
Code – Output –
def fun(x):
Value passed 15 ID 138363499753840
print("value",x,"id",id(x))
value 15 id 138363499753840
x=15
print("Value passed ",x,"ID ",id(x))
fun(x)

Python function with return value – a return statement is used to


end the execution of the function call and “returns” the result to the
caller.
Code –
def ad(a,b):
return a+b
def is_true(a):
return bool(a)
r=ad(4,5)
print("Result of function is :",r) Output –
r=is_true(2<5) Result of function is : 9
print("Result of is_true :",r) Result of is_true : True

Lambda function – a lambda function is a small anonymous function.


A lambda function can take any number of arguments, but can have
only one expression.
Code – Output –
x = lambda a : a + 10
15
print(x(5))

Resursive function – when a function call itself then this type of


construct are termed as recursive function.
Code – Output –
def tri_recursion(k):
Recursion Example Results
if(k>0):
1
result = k+tri_recursion(k-1)
3
print(result)
6
else:
10
result = 0
15
return result
21
print("\n\nRecursion Example Results")
tri_recursion(6)
LAB – 7
Aim – To study OOPS concepts in python.

OOPS Concepts – object-oriented programming(OOP) is a method


of structuring a program by bundling related properties and
behaviours into individual objects.

Object – the object is an entity that has a state and behaviour


associated with it. Any single integer or any single string is an object.

Class – a class is a collection of objects. A class contains the blueprint


or the prototype from which the objects are being created. It is a
logical entity that contains some attributes and methods.

Some points on python class –


 Classes are created by keyword (class).
 Attributes are the variables that belongs to a class.
 Attributes area always public and can be accessed using the
dot(.) operator.
 Class is a user defined data type.

Creating an object –

1. The python self – Class methods must have an extra first


parameter in the method definition.We do not give a value for
this parameter when we call the method,Python provides it.
If we have a method that takes no arguments then we still have
one argument.
Code – Output –
class MCA:
def subject(self,subject):
Python
self.subject=subject
def marks(self,marks): 80
self.marks=marks
def show_subject(self):
return self.subject
def show_marks(self):
return self.marks
Isha = MCA()
Isha.subject("Python")
Isha.marks(80)
print(Isha.show_subject())
print(Isha.show_marks())

2. Python __init__method – The __init__ method is a special


method(constructor) that initializes an instance of the class. It
takes two parameters: self (referring to the instance being
created) and the name parameter is used to assign a name
attribute to each instance of class.
It is run as soon as an object of a class is instantiated. The
method is useful to do any initialization you want to do with
your object.
Code – Output –
class MCA:
def __init__(self,name): Nandita is learning Python
self.name=name Nandita plays badminton
def subject(self):
print(f"{self.name} is learning Python")
def sports(self):
print(f"{self.name} plays badminton")
Nandita = MCA("Nandita")
Nandita.subject()
Nandita.sports()

Inheritance – inheritance is the capability of one class to derive


the properties from another class. The class that derives
properties is called derived class or child class and the class
from which the properties are being derived is called the base
class or parent class.
The benefits of inheritance are :
● It represents real-world relationships well.
● It provides the reusability of a code. We don’t have to write
the same code again and again. Also it allows us to add more
features to a class without modifying it.
● It is transitive in nature, which means that if class B inherits
from another class A, then all the subclasses of B automatically
inherit from class A.
Code –
class animal:
def speak(self):
print("Animal speaking")
class dog(animal):
def bark(self):
print("Dog barking")
d = dog() Output –
Dog barking
d.bark()
d.speak() Animal speaking

Polymorphism – polymorphism simply means having many


forms. Polymorphism let us define methods in the child class
that have the same name as the methods in the parent class. In
inheritance, the child class inherits the methods from the
parent class. However, it is possible to modify a method in a
child class that it has inherited from the parent class.
Code – Output –
class student:
def __init__(self,name): Isha likes python !
self.name=name Neha likes os !
class python(student):
def likes(self): Nandita likes maths !
return f"{self.name} likes python !"
class os(student):
def likes(self): === Code Execution
return f"{self.name} likes os !" Successful ===
class maths(student):
def likes(self):
return f"{self.name} likes maths !"
p = python("Isha")
q = os("Neha")
r = maths("Nandita")
cls=[p,q,r]
for student in cls:
print(student.likes())
LAB – 8
Aim – WAP to print pyramid pattern in python.

Code –
def full_pyramid(n):
for i in range(1, n + 1):

for j in range(n - i):


print(" ", end="")

for k in range(1, 2*i):


print("*", end="")
print()

full_pyramid(5)

Output –

*
***
*****
*******
*********
LAB – 9
Aim – WAP to generate the fibonacci series.

Code –
n = 10
num1 = 0
num2 = 1
next_number = num2
count = 1
while count <= n:
print(next_number, end=" ")
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print()

Output –

1 2 3 5 8 13 21 34 55 89
LAB – 10
Aim – WAP to check whether a given number is an
Armstrong number.

Code –
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Output –

Enter a number: 153


153 is an Armstrong number
LAB – 11
Aim – WAP to check whether a given number is
prime or not.

Code –
num = 29
flag = False
if num == 0 or num == 1:
print(num, "is not a prime number")
elif num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

Output –

29 is a prime number
LAB – 12
Aim – WAP to calculate factorial of a number using
recursion.

Code –
def factorial(x):

if x == 1 or x == 0:
return 1
else:
return (x * factorial(x-1))

num = 7
result = factorial(num)
print("The factorial of", num, "is", result)

Output –

The factorial of 7 is 5040

You might also like