Internal Assignment
NAME NAMAN SHARMA
ROLL NO 2314508772
SEMESTER V
SUBJECT DCA3104 – PYTHON PROGRAMMING
PROGRAM BACHELOR OF COMPUTER
APPLICATIONS (BCA)
Question 1Explain different types of data types used in python?
Answer :- Python has a variety of built-in data types that help store, manage, and work with
different kinds of data in a program. These data types let the programmer know what kind of
value a variable can hold and what actions can be done with it. Python makes it easy to use
these data types, and you don’t need to declare them explicitly, which makes the language
simple and flexible. One of the most common data types in Python is the numeric type. This
is used for storing numbers and includes integers, floating-point numbers, and complex
numbers. Integers are whole numbers, like 5 or -10. Floating-point numbers are for decimal
values, such as 3.14, and are useful when you need more precision, like in measurements or
calculations. Complex numbers have a real and an imaginary part and are mostly used in
scientific and mathematical work.
Another key data type is the [Link] are used to hold text and are written inside single
quotes, double quotes, or triple quotes. They can include letters, numbers, symbols, and spaces.
Python offers many built-in functions to handle strings, such as finding their length, changing
their case, slicing parts of them, and combining them. However, once a string is created, you
can’t change it, which means strings are immutable. The list is a data type that holds a collection
of items in a specific order and can be changed. Lists can contain different types of data, such
as numbers, strings, or even other lists. They are written using square brackets. Because they
are easy to modify, adding, removing, or changing items in a list is straightforward, making
them great for dynamic data.
The tuple is similar to a list, but it is immutable, meaning its contents can’t be changed after it
is created. Tuples are written using parentheses. Since they can’t be altered, tuples are more
secure and are often used for data that should stay fixed during a program's run. Python also
includes the set data type, which is for storing unique elements. A set is unordered and doesn’t
allow duplicates. Sets are helpful when you need to ensure all elements are unique or when
you're performing tasks like removing duplicates, or doing operations like union, intersection,
and difference. The dictionary data type stores data as key-value pairs. Each key is unique and
is used to find its corresponding value. Dictionaries are written using curly braces and are
efficient for storing and retrieving data. They are commonly used for mapping data, such as
keeping track of student records, user details, or configuration settings. The boolean data type
represents logical values and can only be True or False. Booleans are used in decision-making
and for controlling the flow of a program, such as in if-else statements.
In addition to these, Python includes the None type, which represents the absence of a value.
It's often used to initialize variables or to show that a variable hasn't yet been assigned a
meaningful value. In summary, Python's data types offer flexibility and efficiency in handling
various data types. Understanding these types is crucial for writing clear, effective, and error-
free Python programs.
Question 2 How are local and global variables different from each other? Explain use of
global keywords with example?
Answer :- In Python, variables are used to store data that can be accessed and changed while a
program is running. Depending on where they are declared and how they can be accessed,
variables are generally divided into two types: local variables and global variables. It's
important to understand the difference between these two types because it helps in writing
clear, efficient, and error-free code. A local variable is created inside a function. It can only be
used within that function. Once the function is done running, the local variable is no longer
available. Local variables are helpful because they prevent name conflicts, make programs
more secure, and easier to debug. They also help manage memory efficiently since they only
exist while the function is running.
A global variable, on the other hand, is declared outside all functions, typically at the beginning
of a program. It can be accessed from anywhere in the program, including inside functions.
These variables stay in memory for the entire duration of the program. They are useful when
multiple functions need to use the same data. However, using too many global variables is not
recommended because it can make the program harder to understand, maintain, and debug. The
main difference between local and global variables is in their scope, lifetime, and how
accessible they are. Local variables are limited to a specific function and exist only while that
function is running. Global variables can be accessed anywhere in the program and remain in
memory for the whole time the program is running. Changes to a local variable only affect that
function, while changes to a global variable can affect the entire program. In Python, global
variables can be accessed inside a function, but they cannot be directly changed unless the
global keyword is used. The global keyword lets Python know that the variable being used
inside the function is a global one, not a local one. Without this keyword, Python automatically
treats any variable assigned inside a function as local by default. The global keyword is mainly
used when a function needs to change the value of a global variable. By declaring a variable as
global within a function, any changes made to it will affect the variable globally.
Example :-
x = 10 # global variable
def change_value():
global x
x = 20 # modifies the global variable
change_value()
print(x)
Question 3 What is list? Explain different methods to delete an item from list
Answer :- In Python, a list is one of the most commonly used data types. It is used to store a
collection of items in a single variable. A list can contain elements of different types like
numbers, strings, or even other lists. Lists are ordered, meaning each item has a specific
position called an index, which starts from zero. One of the key features of a list is that it is
mutable, which means its elements can be changed, added, or removed after the list is
created. Lists are widely used because they are flexible and easy to work with. There are
several ways to delete or remove items from a list in Python, depending on what you need.
One common method is using the remove() method. This method deletes the first occurrence
of a specified value from the list. It is useful when you know the value you want to remove
but not its position. If the value is not in the list, Python raises an error. So, it is often used
when the programmer is certain that the item exists in the list. Another method to delete an
item from a list is the pop() method.
The pop() method removes an element based on its index position and also returns the
removed item. If no index is provided, it removes and returns the last element of the list. This
method is helpful when you want to remove an item and use its value later in the program. It
is commonly used when elements are processed and removed one at a time. The del keyword
is another way to remove items from a list. Unlike remove() and pop(), del is not a method
but a Python statement. It can be used to delete an item at a specific index, a range of items,
or even the entire list. This makes del a powerful tool when you need more control over
which elements are removed. However, del does not return the deleted item. Python also
allows you to delete multiple items using list slicing along with the del keyword. By
specifying a range of indexes, several elements can be removed at once. This method is
useful when you want to delete a portion of a list rather than a single element. Another
approach is using clear(), which removes all items from the list and makes it empty. This
method is useful when the list is no longer needed but the variable itself must be kept for
future use. Unlike del, clear() does not delete the list variable, only its contents. In some
cases, items can also be removed using list comprehension by creating a new list that
excludes certain elements. Although this does not modify the original list directly, it is a
useful technique when you want to filter out unwanted values based on conditions. a list in
Python is a flexible and powerful data structure used to store multiple values. Python
provides several methods such as remove(), pop(), del, clear(), and slicing to delete items
from a list. Choosing the right method depends on whether the deletion is based on value,
index, or condition, and whether the removed item needs to be reused.
Question 4 a) Explain the utility of break, continue, and pass statement using example.
b) What does the self-argument signify in the class methods?
Answer :- Utility of break, continue, and pass statements in Python (with examples)
In Python, break, continue, and pass are control statements used inside loops to manage the
flow of execution. Each statement serves a different purpose and helps make programs more
flexible and readable.
The break statement is used to immediately terminate a loop when a certain condition is met.
Once the break statement is executed, the loop stops running, and control moves to the
statement after the loop. It is commonly used when the desired result is found and there is no
need to continue looping. For example, if a program searches for a specific number in a list,
the loop can stop as soon as the number is found.
Example:
numbers = [1, 3, 5, 7, 9]
for n in numbers:
if n == 5:
break
print(n)
In this example, the loop stops when the value 5 is encountered, so only 1 and 3 are printed.
The continue statement is used to skip the current iteration of a loop and move directly to the
next iteration. Unlike break, it does not stop the loop entirely; it only skips the remaining code
for the current cycle. Continue is useful when certain values should be ignored during
processing.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Here, when i becomes 3, the continue statement skips the print statement, so 3 is not printed,
but the loop continues with the next values. The pass statement is a null or placeholder
statement. It does nothing when executed. Pass is used where a statement is syntactically
required, but no action is needed at that moment. It is helpful during program development
when code is incomplete or when defining empty blocks like functions, classes, or conditional
statements.
Example:
for i in range(3):
if i == 1:
pass
else:
print(i)
In this case, pass does nothing when i is 1, and the loop continues normally.
b) Meaning of the self argument in class methods
In Python, self is a special parameter used in class methods to refer to the current instance of
the class. It allows access to the object’s variables and methods from within the class. The self
parameter is not a keyword, but it is a naming convention that is widely followed in Python
programming. When a class is defined and an object is created from it, self represents that
specific object. It helps distinguish between instance variables and local variables inside
methods. Without self, Python would not know which object’s data is being accessed or
modified.
Example:
class Student:
def init_(self, name, marks):
[Link] = name
[Link] = marks
def display(self):
print([Link], [Link])
s1 = Student("Aman", 85)
[Link]()
In this example, [Link] and [Link] refer to the variables belonging to the object s1. The
self argument ensures that each object maintains its own data. The self parameter is also
important for calling one method from another within the same class. It provides a clear link
between methods and the object they belong to.
Q5 What is exception handling? Explain the process of creating user defined exception with
code in python.?
Answer :- Exception handling in Python is a way to deal with errors that happen while a
program is running, so the program doesn’t stop suddenly. An error, or exception, can happen
in many ways, like dividing a number by zero, trying to open a file that isn't there, or using an
index that's out of range. If these errors aren't handled, the program might crash and show an
error message. With exception handling, programmers can catch these errors and respond to
them in a smart and helpful way, which makes the program more reliable and better for users.
Python uses the try-except block to manage exceptions. The code that might cause an error
goes inside the try block, and the code that handles the error goes inside the except block. If
an error happens in the try block, Python moves the control to the matching except block and
doesn’t stop the program. Python also has else and finally blocks. The else block runs if no
error occurs, and the finally block runs whether an error happens or not. This setup helps
separate the regular code from the error handling, making it easier to read and maintain.
Besides handling built-in exceptions, Python lets programmers create their own custom
exceptions.
These are special error types made for situations not covered by the built-in exceptions. They
are useful when a program needs to follow its own rules or logic. For example, a banking app
might need an exception for when there's not enough money, or an academic system might
need one for invalid [Link] create a user-defined exception in Python, you define a new
class that inherits from the built-in Exception class.
This makes the new exception part of Python’s exception system, so it can be raised and
handled like any other exception. The custom exception class can have a constructor to
include an error message or other details if needed. Once the user-defined exception is
created, you can raise it using the raise keyword when a specific condition is met.
The raise statement tells the program that an error has occurred at that point, helping to
clearly signal that an error condition has been found based on the program's logic.
class InvalidAgeError(Exception):
def __init__(self, message):
[Link] = message
def check_age(age):
if age < 18:
raise InvalidAgeError("Age must be 18 or above")
else:
print("Access granted")
try:
check_age(15)
except InvalidAgeError as e:
print([Link])
Q6 Explain DDL, DML, DCL and TCL commands in detail.?
Answer :- In database systems, SQL is a language used to work with data stored in relational
databases. It helps in creating, managing, and controlling data. SQL is divided into four main
categories of commands: DDL, DML, DCL, and TCL. Each category has a specific role in
how databases are handled. Knowing these types of commands is important for designing
databases, handling data, and keeping data secure. DDL commands are used to set up and
change the structure of database parts like tables, schemas, indexes, and views. These
commands deal with how the database is organized, not the actual data inside. Examples of
DDL commands are CREATE, ALTER, DROP, and TRUNCATE. CREATE is used to build
new database items like tables or databases. ALTER is for changing what's already there,
such as adding or removing columns from a table. DROP is for removing database items
completely. TRUNCATE deletes all the data from a table but keeps the table's structure.
These DDL commands automatically save changes, so they can't be undone later. DML
commands are used to handle and change the data in database tables. They let users add,
change, retrieve, and remove records. Common DML commands include INSERT, UPDATE,
DELETE, and SELECT. INSERT adds new data to a table. UPDATE changes existing data.
DELETE removes data based on certain conditions. SELECT is for getting data from one or
more tables. DML commands are used a lot in applications to manage everyday database
tasks. DCL commands are for controlling who can access or change data in the database.
They help set permissions and ensure safety by letting you decide who can do what. The
main DCL commands are GRANT and REVOKE. GRANT gives users or roles certain rights,
like reading or adding data. REVOKE takes away those rights. DCL commands are key to
keeping the database secure and making sure only the right people can perform certain
actions. TCL commands are used to manage transactions in the database. A transaction is a
set of SQL statements that are carried out together as one unit. TCL commands help keep data
accurate and consistent. Examples of TCL commands are COMMIT, ROLLBACK, and
SAVEPOINT. COMMIT permanently saves all the changes made during a transaction.
ROLLBACK undoes any changes made since the last commit. SAVEPOINT sets a point in a
transaction where you can go back to if needed. TCL commands are especially important in
situations where data needs to be precise and reliable.