0% found this document useful (0 votes)
2 views8 pages

DCA2205 Python Programming

The document provides an overview of Python programming concepts, including data types, file handling, and object-oriented programming principles like encapsulation. It discusses the differences between mutable and immutable types, the use of operators, and the importance of variable-length arguments and recursion. Additionally, it covers database connectivity in Python, including DDL and DML commands for managing data.

Uploaded by

Md Tauhid
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)
2 views8 pages

DCA2205 Python Programming

The document provides an overview of Python programming concepts, including data types, file handling, and object-oriented programming principles like encapsulation. It discusses the differences between mutable and immutable types, the use of operators, and the importance of variable-length arguments and recursion. Additionally, it covers database connectivity in Python, including DDL and DML commands for managing data.

Uploaded by

Md Tauhid
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

NAME WASIM HAIDAR

ROLL NUMBER 2414517584

SEMESTER IV

COURSE CODE DCA2205

COURSE NAME
Python Programming
Answer 1:
a. Data Types in Python
Python provides several built-in data types used to store different kinds of values. Python is
dynamically typed, so the type of a variable is decided automatically at runtime. The main data
types are:
• Numeric types: int for whole numbers like 10, float for decimal numbers like 3.14, and
complex for numbers with a real and imaginary part like 2+3j.
• String (str): a sequence of characters written in quotes, such as "Hello".
• List: an ordered, changeable (mutable) collection written in square brackets, such as
[1, 2, 3].
• Tuple: an ordered but unchangeable (immutable) collection written in parentheses,
such as (1, 2, 3).
• Dictionary (dict): an unordered collection of key–value pairs, such as {"name": "Ali",
"age": 20}.
• Set: an unordered collection of unique items, such as {1, 2, 3}.
• Boolean (bool): represents the two values True and False.
• NoneType: represents the special value None, meaning no value.
Data types are also classified as mutable (can be changed, like list, set, and dictionary) or
immutable (cannot be changed, like int, float, string, and tuple). Understanding data types is
important in Python because each type supports different operations; numbers can be used in
arithmetic, strings in text processing, and lists or dictionaries in storing groups of related data.
Python also allows converting one type into another using functions like int(), float(), and str(),
which is called type casting.

b. Membership and Identity Operators


Membership operators check whether a value is present in a sequence such as a list, string, or
tuple. The two membership operators are "in", which returns True if the value is found, and
"not in", which returns True if the value is not found.
fruits = ["apple", "banana", "mango"]
print("apple" in fruits) # True
print("orange" not in fruits) # True
Identity operators check whether two variables refer to the same object in memory, not just
whether their values are equal. The two identity operators are "is", which returns True if both
names point to the same object, and "is not", which returns True if they point to different
objects.
a = [1, 2, 3]
b=a
c = [1, 2, 3]
print(a is b) # True (same object)
print(a is c) # False (equal values, different objects)
Thus, membership operators test the presence of a value in a sequence, while identity operators
test whether two names refer to the same object. These operators are commonly used inside
conditions and loops to make decisions and comparisons in a program.

Answer 2:
a. Role of File Modes in File Handling
In Python, file handling is done using the open() function, which needs a file name and a file
mode. The file mode tells Python what operation is to be performed, such as reading, writing,
or appending, and whether the file is treated as text or binary. Choosing the correct file mode
is important because it decides how data is read or written and whether existing data is kept or
erased. The main file modes are:
• "r" (read): opens a file for reading and gives an error if the file does not exist. It is the
default mode.
• "w" (write): opens a file for writing; it creates the file if needed and erases all existing
content if the file already exists.
• "a" (append): opens a file to add new data at the end without deleting the existing
content.
• "r+" (read and write): opens a file for both reading and writing.
• "x" (create): creates a new file and gives an error if the file already exists.
• "b" (binary): added to other modes, such as "rb" or "wb", to work with binary files
like images.
f = open("[Link]", "w")
[Link]("Hello")
[Link]()
In this way, file modes decide the purpose and behaviour of every file operation. By default,
files are opened in text mode, where data is read and written as strings, while binary mode is
used for non-text data such as images and audio. Selecting the wrong mode can lead to loss of
data, for example opening an existing file in write mode erases its contents, so the append mode
is used when old data must be preserved.

b. Adding a New Data Item into a List


A list in Python is a mutable data structure, so new items can be added to it at any time. Python
provides several methods to add data items into a list:
• append(): adds a single item to the end of the list.
• insert(): adds an item at a specific position (index) in the list.
• extend(): adds all items of another list or iterable to the end of the current list.
• + operator: joins two lists together to form a new combined list.
nums = [1, 2, 3]
[Link](4) # [1, 2, 3, 4]
[Link](1, 10) # [1, 10, 2, 3, 4]
[Link]([5, 6]) # [1, 10, 2, 3, 4, 5, 6]
nums = nums + [7] # adds 7 at the end
Among these, append() adds one item at the end, insert() adds an item at a chosen position,
extend() adds many items, and the + operator combines lists, making it easy to grow a list as
required.

Answer 3:
a. Tuples versus Lists and Tuple Methods
A list and a tuple both store an ordered collection of items, but they differ in important ways:
• Mutability: a list is mutable, so its items can be changed, added, or removed, while a
tuple is immutable and cannot be changed after creation.
• Syntax: a list is written using square brackets [ ], while a tuple is written using
parentheses ( ).
• Methods: a list has many built-in methods, while a tuple has only a few because it
cannot be modified.
• Performance and use: tuples are faster and use less memory, and because they are
immutable they can be used as dictionary keys, which lists cannot.
Since tuples cannot be changed, they support only two built-in methods: count(), which returns
how many times a value appears, and index(), which returns the position of the first occurrence
of a value. Because a list can be modified, it is used when the data may change during the
program, while a tuple is used when the data should stay constant, such as fixed coordinates or
configuration values. This immutability also makes tuples safer, since their contents cannot be
changed by mistake, and it allows Python to store them more efficiently.
t = (10, 20, 10, 30)
print([Link](10)) # 2
print([Link](20)) # 1

b. Dictionary and Adding or Removing Data


A dictionary in Python is an unordered, mutable collection of data stored as key–value pairs.
Each key is unique and is used to access its value. Dictionaries are written using curly braces
{ }, with each item in the form key: value, for example student = {"name": "Ali", "age": 20}.
New data can be added by assigning a value to a new key or by using the update() method.
Data can be removed using pop(key), which removes an item by key and returns its value; del,
which deletes an item by key; popitem(), which removes the last inserted item; and clear(),
which removes all items.
student = {"name": "Ali", "age": 20}
student["course"] = "Python" # add a new key
[Link]({"city": "Delhi"}) # add using update()
[Link]("age") # remove by key
del student["name"] # remove using del
Thus, a dictionary stores data as key–value pairs and allows easy adding and removing of items
using these built-in operations. Dictionaries are very useful because they allow fast access to
values using their keys instead of numeric positions, which makes them ideal for storing related
information such as the record of a student or the details of a product.

Answer 4:
a. Variable Length and Keyword Arguments
In Python, functions can accept a variable number of arguments using special symbols, which
is useful when the number of arguments is not fixed in advance.
By writing a parameter with a single asterisk, such as *args, a function can accept any number
of positional arguments, which are collected into a tuple inside the function.
def add(*numbers):
return sum(numbers)
print(add(1, 2, 3)) # 6
print(add(5, 10)) # 15
By writing a parameter with two asterisks, such as **kwargs, a function can accept any number
of keyword arguments (name=value pairs), which are collected into a dictionary inside the
function.
def show(**details):
for key, value in [Link]():
print(key, "=", value)
show(name="Ali", age=20)
Thus, *args handles a variable number of positional arguments as a tuple, while **kwargs
handles a variable number of keyword arguments as a dictionary, making functions more
flexible. Normal arguments must match in number and order, but variable length and keyword
arguments remove this restriction, which is helpful when writing general-purpose functions
such as one that adds any quantity of numbers or prints any set of details. Both can also be
combined with normal arguments in the same function, as long as they are written in the correct
order.

b. Types of Recursion
Recursion is a technique in which a function calls itself to solve a problem by breaking it into
smaller sub-problems. A recursive function must have a base condition to stop the calls. The
main types of recursion are described below.
In direct recursion, a function calls itself directly. For example, a function to find the factorial
of a number:
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(5)) # 120
In indirect recursion, a function calls another function, which in turn calls the first function, for
example function A calls B, and B calls A. In tail recursion, the recursive call is the last
statement in the function, so nothing is left to do after the call returns. In every type of
recursion, a base condition is essential to prevent infinite recursion and a program crash.
Recursion is useful for problems that can be defined in terms of smaller versions of themselves,
such as factorial, the Fibonacci series, and traversing tree structures. However, recursion uses
more memory than loops because each call is stored on the call stack, so it should be used only
when it makes the solution simpler and clearer.

Answer 5:
Encapsulation is one of the main features of object-oriented programming. It is the concept of
wrapping data (variables) and the methods (functions) that operate on that data together into a
single unit called a class. Encapsulation also means hiding the internal details of an object and
allowing access to the data only through defined methods, which protects the data from
accidental or unauthorized changes from outside the class.
In Python, encapsulation is implemented using classes. Data can be made private by adding an
underscore prefix to a variable name: a single underscore (_name) indicates a protected
member, while a double underscore (__name) makes a member private so it cannot be accessed
directly from outside the class. Such data is then accessed and changed using special methods,
often called getter and setter methods. The main benefits of encapsulation are data protection,
better security, and increased modularity, because the internal working of a class can be
changed without affecting the rest of the program. Encapsulation is similar to a medicine
capsule that keeps different ingredients safely wrapped inside a single cover; in the same way,
a class keeps its data and methods together and hides sensitive data from the outside world,
which makes large programs easier to manage.
class Account:
def __init__(self, balance):
self.__balance = balance # private variable
def get_balance(self):
return self.__balance

Class Variables versus Instance Variables


A class variable is a variable that is shared by all objects (instances) of a class. It is defined
inside the class but outside any method, and it has the same value for every object unless it is
changed specifically. An instance variable belongs to a particular object; it is usually defined
inside the __init__ method using the self keyword, and each object has its own separate copy.
A class variable can be accessed using either the class name or an object, while an instance
variable is accessed only through its own object.
class Student:
college = "MUJ" # class variable (shared)
def __init__(self, name):
[Link] = name # instance variable (unique)
Here, college is a class variable shared by all students, while name is an instance variable that
is different for each student. In short, class variables are common to all objects of the class,
whereas instance variables are unique to each object. Choosing between them depends on
whether a value should be common to every object, such as the name of the college, or specific
to each object, such as the name of an individual student.

Answer 6:
Python can connect to databases such as MySQL and SQLite to store and manage data, using
a database connector module, for example [Link] for MySQL. Database connectivity
allows a Python program to store data permanently, retrieve it, and update it, which is essential
for real applications such as banking, e-commerce, and record management. Python follows a
standard approach for this, using a connector module that acts as a bridge between the program
and the database. The main steps for database connectivity in Python are:
• Import the module: import the database connector, such as import [Link].
• Establish a connection: create a connection to the database by giving the host,
username, password, and database name.
• Create a cursor object: the cursor is used to execute SQL queries and fetch results.
• Execute SQL queries: use the cursor's execute() method to run SQL commands.
• Commit the changes: use commit() to save changes made by commands that modify
data.
• Close the connection: close the cursor and connection to free resources.
import [Link]
con = [Link](host="localhost", user="root",
password="1234", database="school")
cur = [Link]()
[Link]("SELECT * FROM students")
[Link]()
[Link]()
After running a SELECT query, the results can be read using methods such as fetchone(), which
returns a single row, or fetchall(), which returns all the rows returned by the query.

DDL and DML Commands


SQL commands are mainly divided into DDL and DML. DDL (Data Definition Language)
commands are used to define and modify the structure of database tables. Common DDL
commands are CREATE (to create a table), ALTER (to change a table's structure), DROP (to
delete a table), and TRUNCATE (to remove all rows).
CREATE TABLE students (id INT, name VARCHAR(20));
DML (Data Manipulation Language) commands are used to work with the data stored in tables.
Common DML commands are INSERT (to add data), UPDATE (to modify data), DELETE
(to remove data), and SELECT (to retrieve data).
INSERT INTO students VALUES (1, 'Ali');
In short, database connectivity in Python involves connecting to the database, creating a cursor,
executing queries, and closing the connection, while DDL commands define the structure of
the database and DML commands work with the actual data inside it. The key difference is that
DDL commands affect the structure or schema of the database, whereas DML commands affect
only the data stored within that structure. It is also good practice to handle errors using try and
except blocks so that the program does not crash if the connection or a query fails.

You might also like