0% found this document useful (0 votes)
34 views13 pages

Python Programming Muj Assignment

The document provides an overview of various Python programming concepts, including data types, file handling, recursion, encapsulation, and database connectivity. It explains the differences between lists and tuples, the role of file modes, and methods for adding items to lists. Additionally, it covers the importance of encapsulation in object-oriented programming and outlines DDL and DML commands for database management.

Uploaded by

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

Python Programming Muj Assignment

The document provides an overview of various Python programming concepts, including data types, file handling, recursion, encapsulation, and database connectivity. It explains the differences between lists and tuples, the role of file modes, and methods for adding items to lists. Additionally, it covers the importance of encapsulation in object-oriented programming and outlines DDL and DML commands for database management.

Uploaded by

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

NAME AFREEN KALANDAR MALDAR

ROLL NUMBER 2414503094

PROGRAM BACHELOR OF COMPUTER


APPLICATION (BCA)

SEMESTER 4

COURSE CODE & NAME DCA2205 & PYTHON PROGRAMMING

SET-I

Q. No 1)
Answer: a) Data Types Used in Python

Data types in Python define the type of value stored in a variable. Python provides different
built in data types for storing and processing various forms of data efficiently.

Numeric data types are used for storing numbers. The int type stores whole numbers such as
x = 10, float stores decimal numbers such as y = 12.5, and complex stores complex numbers
such as z = 3 + 4j.

String data type is used for storing characters and text enclosed within single or double
quotes. Example: name = "Python". Strings support operations like concatenation and slicing.
List is an ordered and mutable collection of elements enclosed within square brackets.
Example: marks = [45, 67, 89]. Lists allow duplicate values and elements can be modified
after creation.

Tuple is an ordered but immutable collection enclosed within parentheses. Example: data =
(10, 20, 30). Tuple elements cannot be changed after creation.

Set is an unordered collection of unique elements enclosed within curly braces. Example: s =
{1, 2, 3}. Sets do not allow duplicate values.

Dictionary stores data in key value pairs. Example: student = {"name":"Ravi", "age":20}.
Dictionaries are useful for storing related information.

Boolean data type stores only two values, True and False. It is mainly used in conditions and
decision making statements.

b) Membership and Identity Operators

Membership operators are used to check whether a value exists in a sequence such as a list,
tuple, set, or string. Python provides two membership operators: in and not in.

Example:

numbers = [10, 20, 30]

print(20 in numbers)

Output: True

The operator checks whether the value 20 is present in the list.

Example:

name = "Python"

print("J" not in name)

Output: True

Since the character J is not present in the string, the result becomes true.

Identity operators are used to check whether two variables refer to the same object in
memory. Python provides two identity operators: is and is not.

Example:

a = [1, 2]

b=a
print(a is b)

Output: True

Both variables refer to the same object in memory.

Example:

x = [1, 2]

y = [1, 2]

print(x is y)

Output: False

Even though both lists contain the same values, they are stored as different objects.

Thus, Python data types help in storing different kinds of information, while membership and
identity operators help in checking relationships between values and objects.

Q. No 2)
Answer: a) Role of File Modes in File Handling

File handling in Python is used to create, read, write, and manage files. File modes play an
important role because they specify how a file should be opened and what operations can be
performed on it. Different modes allow users to read data, write new data, append
information, or work with binary files.

The r mode is used for reading data from a file. The file must already exist. Example:
open("[Link]","r")

The w mode is used for writing data into a file. If the file already exists, its old content is
removed. If the file does not exist, a new file is created. Example: open("[Link]","w")

The a mode is used to append data at the end of an existing file without deleting previous
content. Example: open("[Link]","a")

The x mode creates a new file and gives an error if the file already exists.

Binary modes such as rb and wb are used for binary files like images, videos, and audio files.

The r+ mode allows both reading and writing operations in the same file.

File modes are important because they control file access, prevent accidental data loss, and
help manage files safely and efficiently.
b) Methods of Adding New Data Item into List

A list is an ordered and mutable data structure in Python used to store multiple values. Python
provides different methods for adding new elements into a list.

The append() method adds a single element at the end of the list.

Example:

numbers = [1, 2, 3]

[Link](4)

Output: [1, 2, 3, 4]

The insert() method adds an element at a specified position.

Example:

[Link](1, 10)

Output: [1, 10, 2, 3, 4]

The extend() method adds multiple elements from another list.

Example:

[Link]([5, 6])

Output: [1, 10, 2, 3, 4, 5, 6]

The + operator combines two lists and creates a new list.

Example:

a = [1, 2]

b = [3, 4]

c=a+b

Output: [1, 2, 3, 4]

Thus, file modes help control file operations effectively, while Python lists provide different
methods for adding new data items easily and efficiently.

Q. No 3)
Answer: a) Difference Between Tuple and List
Tuple and list are important data structures in Python used for storing collections of elements.
Even though both can store multiple values, they differ in many ways. A list is an ordered
and mutable collection enclosed within square brackets, whereas a tuple is an ordered and
immutable collection enclosed within parentheses. Since lists are mutable, elements can be
added, removed, or modified after creation. Tuples cannot be modified once created. Lists
consume more memory and are slower compared to tuples, while tuples are faster and more
memory efficient. Tuples also provide better security because their values remain constant
throughout the program.

Example:
List: marks = [10, 20, 30]
Tuple: data = (10, 20, 30)

Python provides built in methods for tuples. The count() method returns the number of times
a specified value occurs in the tuple. Example:

t = (1, 2, 2, 3)

print([Link](2))

Output: 2

The index() method returns the index position of a specified element.

Example:

t = (10, 20, 30)

print([Link](20))

Output: 1

Thus, lists are mainly used when data needs modification, whereas tuples are preferred when
fixed data is required.

b) Dictionary

A dictionary is a Python data structure used to store data in the form of key value pairs.
Dictionaries are enclosed within curly braces and each key must be unique. Dictionaries are
very useful for storing related information and provide fast data access using keys.

Example:

student = {"name":"Ravi", "age":21}

Data can be added into a dictionary by assigning values to new keys.

Example:

student["city"] = "Bangalore"
Output:

{"name":"Ravi", "age":21, "city":"Bangalore"}

The update() method can also be used to add multiple items into the dictionary.

Example:

[Link]({"course":"BCA"})

Different methods are available for removing data from a dictionary. The pop() method
removes a specified key and returns its value.

Example:

[Link]("age")

The del statement is used to delete a particular item.

Example:

del student["city"]

The clear() method removes all items from the dictionary.

Example:

[Link]()

Thus, dictionaries are flexible and efficient data structures used for storing and managing
information in key value form.

SET-II

Q. No 4)
Answer: a) Variable Length and Keyword Arguments in Python

In Python, functions can accept different types of arguments to make programs flexible and
easy to use. Variable length arguments are used when the exact number of arguments is not
known in advance. Python provides *args and **kwargs for this purpose.

The *args argument allows a function to accept multiple positional arguments. The values are
stored in the form of a tuple.
Example:

def add(*numbers):

print(numbers)

add(10, 20, 30)

Output: (10, 20, 30)

The **kwargs argument allows a function to accept multiple keyword arguments. The values
are stored in the form of a dictionary.

Example:

def student(**data):

print(data)

student(name="Ravi", age=21)

Output: {'name': 'Ravi', 'age': 21}

Keyword arguments are arguments passed using parameter names. In keyword arguments,
the order of arguments is not important.

Example:

def display(name, age):

print(name, age)

display(age=20, name="Anil")

Output: Anil 20

Variable length and keyword arguments improve flexibility, readability, and simplify
function handling in Python.

b) Types of Recursion

Recursion is a process in which a function calls itself repeatedly until a stopping condition is
satisfied. Recursion is useful for solving mathematical and complex programming problems.

1. Direct Recursion
In direct recursion, a function directly calls itself.

Example:

def show(n):
if n > 0:

print(n)

show(n-1)

show(3)

Output: 3 2 1

2. Indirect Recursion
In indirect recursion, one function calls another function and the second function
again calls the first function.

Example:
Function A calls Function B and Function B calls Function A.

3. Tail Recursion
In tail recursion, the recursive call is the last statement of the function.

Example:

def fun(n):

if n == 0:

return

return fun(n-1)

4. Non Tail Recursion


In non tail recursion, some operations are performed after the recursive call.

Example:

def fun(n):

if n > 0:

fun(n-1)

print(n)

Recursion reduces code size and simplifies problem solving, but excessive recursion may
increase memory usage and execution time.

Q. No 5)
Answer: Encapsulation
Encapsulation is one of the important concepts of Object Oriented Programming. It is the
process of combining data and methods into a single unit called a class. Encapsulation helps
in protecting data from unauthorized access and modification by restricting direct access to
variables. In encapsulation, data members are usually declared as private and are accessed
through methods. This concept supports data hiding and improves security, reliability, and
maintainability of programs.

Example:

class Student:

def __init__(self):

self.__marks = 0

def setMarks(self, m):

self.__marks = m

def getMarks(self):

return self.__marks

obj = Student()

[Link](85)

print([Link]())

In the above example, the variable marks is private and cannot be accessed directly outside
the class. Access is provided through methods only.

Advantages of encapsulation include improved data security, prevention of unauthorized


access, better code organization, easy maintenance, and increased program reliability.
Encapsulation is widely used in software development to protect sensitive information and
control access to data.

Class Variables and Instance Variables

Variables used inside a class are mainly classified into class variables and instance variables.

Class variables are variables shared by all objects of a class. They are declared inside the
class but outside methods. Only one copy of a class variable exists, and changes made to it
affect all objects of the class.

Example:

class Student:

college = "ABC College"

Here, college is a class variable shared by every object.


Instance variables are variables that belong to individual objects. They are declared inside
methods using the self keyword. Every object has its own separate copy of instance variables.

Example:

class Student:

def __init__(self, name):

[Link] = name

Here, name is an instance variable.

Differences between class variables and instance variables:

1. Class variables are shared among all objects, whereas instance variables are unique
for each object.
2. Class variables are declared outside methods, while instance variables are declared
inside methods.
3. Changes in class variables affect all objects, whereas changes in instance variables
affect only one object.
4. Class variables consume less memory compared to instance variables because only
one copy exists.

Thus, encapsulation protects data by combining variables and methods into a single unit,
while class variables and instance variables help manage shared and object specific data
efficiently.

Q. No 6)
Answer: Database Connectivity in Python

Database connectivity in Python is the process of connecting Python programs with databases
to store, retrieve, update, and manage data. Python provides modules such as
[Link] and sqlite3 for communicating with databases like MySQL and SQLite.
Database connectivity is widely used in banking systems, student management systems,
websites, and business applications.

The first step is importing the database module.

Example:

import [Link]

The second step is establishing a connection between Python and the database using host
name, username, password, and database name.
Example:

con = [Link](

host="localhost",

user="root",

password="1234",

database="college"

The third step is creating a cursor object to execute SQL commands.

Example:

cur = [Link]()

The fourth step is executing SQL queries using the execute() method.

Example:

[Link]("SELECT * FROM student")

The fifth step is fetching data using methods like fetchall() or fetchone().

Example:

result = [Link]()

The sixth step is saving changes using commit().

Example:

[Link]()

The final step is closing the database connection.

Example:

[Link]()

Thus, database connectivity helps Python applications interact with databases efficiently.

DDL Commands

DDL stands for Data Definition Language. These commands are used to define and manage
database structures such as tables and schemas.
1. CREATE
Used to create tables or databases.

Example:

CREATE TABLE Student(

id INT,

name VARCHAR(20)

);

2. ALTER
Used to modify existing tables.

Example:

ALTER TABLE Student ADD age INT;

3. DROP
Used to delete a table or database.

Example:

DROP TABLE Student;

4. TRUNCATE
Used to remove all records from a table.

Example:

TRUNCATE TABLE Student;

DML Commands

DML stands for Data Manipulation Language. These commands are used to insert, update,
delete, and retrieve data from database tables.

1. INSERT
Used to add records into a table.

Example:

INSERT INTO Student VALUES(1, 'Ravi');

2. UPDATE
Used to modify existing records.

Example:
UPDATE Student SET name='Anil' WHERE id=1;

3. DELETE
Used to remove records from a table.

Example:

DELETE FROM Student WHERE id=1;

4. SELECT
Used to retrieve records from a table.

Example:

SELECT * FROM Student;

Thus, DDL commands manage database structure, while DML commands help manage and
manipulate data stored in database tables.

You might also like