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

Python Data Types and Variable Scope Explained

The document provides an overview of various programming concepts in Python, including data types, variable scope, list manipulation, control statements, exception handling, and SQL command categories. It explains built-in data types like numeric, sequence, mapping, set, boolean, and NoneType, as well as the differences between local and global variables. Additionally, it covers methods for deleting items from lists, the significance of the self-argument in class methods, and details on DDL, DML, DCL, and TCL commands in SQL.

Uploaded by

shagunshagun282
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)
26 views8 pages

Python Data Types and Variable Scope Explained

The document provides an overview of various programming concepts in Python, including data types, variable scope, list manipulation, control statements, exception handling, and SQL command categories. It explains built-in data types like numeric, sequence, mapping, set, boolean, and NoneType, as well as the differences between local and global variables. Additionally, it covers methods for deleting items from lists, the significance of the self-argument in class methods, and details on DDL, DML, DCL, and TCL commands in SQL.

Uploaded by

shagunshagun282
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

Centre for Distance & Online Education

NAME SHAGUN

ROLL NUMBER 2314502552

SESSION SEPT 2025

PROGRAM BACHELOR OF COMPUTER APPLICATIONS (BCA)

SEMESTER V

COURSE CODE & NAME DCA3103 – SOFTWARE ENGINEERING

Q1. Explain different types of data types used in Python.

Python provides a rich set of built-in data types that allow programmers to store, manage, and
manipulate data efficiently. These data types are broadly categorized into numeric, sequence,
mapping, set, boolean, and special data types.

Numeric data types are used to store numerical values. The most common numeric types are
int, float, and complex. The int type represents whole numbers of unlimited length, such as 10
or -45. The float type stores decimal values like 3.14 or 0.001. The complex type is used for
complex numbers that have real and imaginary parts, such as 2+3j. Numeric data types are
commonly used in calculations, scientific computing, and financial applications.

Sequence data types store collections of items in an ordered manner. The most widely used
sequence types are list, tuple, and string. A list is a mutable sequence that can store different
types of elements and can be modified after creation. Tuples are similar to lists but are
immutable, making them suitable for fixed data collections. Strings store sequences of
characters and are used to represent text. These data types are essential for handling structured
data.

Mapping data types are used to store data in key-value pairs. The primary mapping type in
Python is the dictionary. Dictionaries allow fast data access using unique keys and are widely
used to represent structured data such as records, configurations, and JSON-like objects.
Centre for Distance & Online Education

Set data types store unordered collections of unique elements. Python provides set and
frozenset. A set is mutable, while a frozenset is immutable. Sets are useful for mathematical
operations like union, intersection, and difference, as well as for removing duplicate values.

Boolean data type stores logical values True or False. It is commonly used in decision-making
and conditional statements.

NoneType represents the absence of a value using None. It is often used to initialize variables or
indicate that no value is returned from a function. Together, these data types form the
foundation of Python programming and enable flexible data handling.

Q2. How are local and global variables different from each other? Explain use of global
keyword with example.

Variables in Python are classified based on their scope, mainly as local variables and global
variables. The scope of a variable determines where it can be accessed and modified within a
program.

A local variable is declared inside a function and can be accessed only within that function. It
exists only during the execution of the function. Local variables help in maintaining data privacy
and avoiding unintended modifications. For example, a variable declared inside a function for
calculation purposes cannot be accessed outside that function.

A global variable is declared outside all functions and can be accessed throughout the program,
including inside functions. Global variables are useful when a value needs to be shared across
multiple functions. However, excessive use of global variables can make programs difficult to
debug and maintain.

By default, if a variable with the same name exists both globally and locally, Python treats the
variable inside the function as local. To modify a global variable inside a function, the global
keyword is used. The global keyword tells Python that the variable refers to the globally
declared variable, not a new local one.

Example:

count = 10 # global variable


Centre for Distance & Online Education

def update():

global count

count = count + 5

update()

print(count)

In this example, count is a global variable. Inside the function update, the global keyword allows
modification of the global variable. Without using global, Python would create a new local
variable named count.

Local variables improve modularity and reduce side effects, while global variables simplify
shared access. Proper understanding of variable scope and controlled use of the global keyword
leads to cleaner and more maintainable Python programs.

Q3. What is a list? Explain different methods to delete an item from a list.

A list is one of the most commonly used data types in Python. It is an ordered, mutable
collection that can store elements of different data types such as integers, strings, and even
other lists. Lists are defined using square brackets and allow dynamic modification, making
them suitable for storing and managing collections of data.

Python provides several methods to delete items from a list, depending on the requirement.
One common method is the remove() method. This method removes the first occurrence of a
specified value from the list. It is useful when the value to be removed is known. However, if the
value does not exist, it raises an error.

Another method is pop(). The pop() method removes and returns the element at a specified
index. If no index is provided, it removes the last element of the list. This method is useful when
both deletion and retrieval of the element are required.
Centre for Distance & Online Education

The del statement is another way to remove elements from a list. It can delete a specific
element using its index or remove a range of elements using slicing. It is also capable of deleting
the entire list from memory.

The clear() method removes all elements from the list, making it empty while keeping the list
object intact. This is useful when the list structure needs to be reused.

Example:

data = [10, 20, 30, 40]

[Link](20)

[Link](1)

del data[0]

[Link]()

Each deletion method serves a specific purpose. Choosing the correct method depends on
whether the deletion is based on value, index, or the need to empty the entire list.

SET–II

Q4.

a) Explain the utility of break, continue, and pass statement using example.

The break, continue, and pass statements are control statements used to alter the flow of loops
in Python.

The break statement is used to terminate a loop immediately when a specific condition is met.
It is commonly used to exit a loop early, even if the loop condition is still true.

Example:

for i in range(1, 6):

if i == 3:
Centre for Distance & Online Education

break

print(i)

The continue statement skips the current iteration of the loop and moves to the next iteration.
It is useful when certain values need to be ignored during execution.

Example:

for i in range(1, 6):

if i == 3:

continue

print(i)

The pass statement does nothing and is used as a placeholder where a statement is syntactically
required but no action is needed.

Example:

for i in range(5):

if i == 2:

pass

else:

print(i)

These statements provide flexibility and control in loop execution, making programs more
efficient and readable.

b) What does the self-argument signify in the class methods?

The self argument represents the current instance of a class. It is used to access variables and
methods associated with the object. Although self is not a keyword, it is a widely accepted
convention in Python.
Centre for Distance & Online Education

When a method is called using an object, Python automatically passes the object reference to
the method as self. This allows instance variables to be accessed and modified within class
methods.

Example:

class Student:

def set_name(self, name):

[Link] = name

def display(self):

print([Link])

Here, [Link] refers to the instance variable of the specific object. Without self, Python would
not be able to distinguish between local variables and instance variables. Thus, self ensures
proper data encapsulation and object-oriented behavior.

Q5. What is exception handling? Explain the process of creating user defined exception with
code in Python.

Exception handling in Python is a mechanism used to handle runtime errors gracefully,


preventing abnormal termination of programs. Errors that occur during execution are called
exceptions. Python uses try, except, else, and finally blocks to handle exceptions.

The try block contains code that may raise an exception. The except block catches and handles
the exception. The else block executes if no exception occurs, and the finally block runs
regardless of whether an exception is raised or not.

Python also allows programmers to create user-defined exceptions to handle application-


specific error conditions. This is done by creating a new class that inherits from the built-in
Exception class.

Example:
Centre for Distance & Online Education

class InvalidAgeError(Exception):

pass

def check_age(age):

if age < 18:

raise InvalidAgeError("Age must be 18 or above")

else:

print("Access granted")

try:

check_age(16)

except InvalidAgeError as e:

print(e)

In this example, a custom exception InvalidAgeError is created. The raise keyword is used to
trigger the exception when a specific condition is met. User-defined exceptions improve
program clarity, allow precise error handling, and make large applications more robust and
maintainable.

Q6. Explain DDL, DML, DCL and TCL commands in detail.

SQL commands are categorized based on their functionality. The major categories are DDL,
DML, DCL, and TCL.

Data Definition Language (DDL) commands are used to define and manage database structures.
Common DDL commands include CREATE, ALTER, DROP, and TRUNCATE. These commands
create tables, modify structures, and remove database objects. DDL commands directly affect
the database schema.
Centre for Distance & Online Education

Data Manipulation Language (DML) commands are used to manage data stored in tables.
Common DML commands include INSERT, UPDATE, DELETE, and SELECT. These commands allow
users to add, modify, remove, and retrieve data. DML commands are frequently used in
application development.

Data Control Language (DCL) commands control access to database objects. The main DCL
commands are GRANT and REVOKE. They are used to provide or remove user permissions,
ensuring data security and controlled access.

Transaction Control Language (TCL) commands manage database transactions. Common TCL
commands include COMMIT, ROLLBACK, and SAVEPOINT. These commands ensure data
consistency by allowing changes to be saved permanently or undone when errors occur.

Together, these SQL command categories help in effective database creation, management,
security, and reliability.

Common questions

Powered by AI

Global variables facilitate data sharing across functions, simplifying shared access. However, they complicate debugging and maintenance due to potential widespread changes impacting functionality. Local variables, specific to function scope, enhance modularity, reduce side effects, and minimize the risk of unintended variable modification, thus supporting cleaner and more maintainable code .

Local variables are declared inside functions and exist only during their execution, ensuring privacy and reducing unintended changes. Global variables exist outside all functions and are accessible throughout the program. The global keyword is used within functions to modify global variables, indicating the reference is to a global variable rather than creating a local one .

DDL (Data Definition Language) defines and modifies schema structures (CREATE, ALTER, DROP). DML (Data Manipulation Language) manages data within tables (INSERT, UPDATE, DELETE, SELECT). DCL (Data Control Language) manages permissions (GRANT, REVOKE). TCL (Transaction Control Language) controls transaction processing (COMMIT, ROLLBACK, SAVEPOINT). They collectively ensure efficient database creation, management, security, and reliable transaction processing .

The break statement exits loops early when a condition is met; continue skips remaining code in the loop's current iteration and starts the next iteration; pass serves as a placeholder having no impact, useful in future iterations. For example, break exits a loop when a certain number is reached, continue skips over a specified number, and pass keeps the loop structure for future code .

Python offers various methods for list item deletion: remove() deletes the first occurrence of a specified value; pop() removes and returns an element by index or last element if no index is given; del deletes elements by index or slices; clear() empties the entire list but retains its structure. The method choice depends on whether deletion is by value, index, or if the entire list needs clearing .

The self argument in class methods allows access to the variables and methods associated with an object, acting as a reference to the class instance itself. It distinguishes between instance and local variables, implementing proper data encapsulation and ensuring each object's state is maintained separately, crucial for object-oriented programming .

User-defined exceptions in Python are created by defining a new class that inherits from the Exception class. They provide a way to represent application-specific error conditions, enabling precise error handling and improving program clarity. This approach fosters robust error management by allowing developers to handle errors in a contextually relevant manner .

The clear() method is advisable when all elements must be removed from a list but the list's structure is to remain intact for reuse. It enables the list to be emptied efficiently without deallocating the list memory space. However, it cannot be used to remove individual elements or to handle specific item conditions, limiting its use in precise element management .

Exception handling in Python, through try, except, else, and finally blocks, prevents abnormal program termination by gracefully managing runtime errors. By catching exceptions, programs can avoid crashes and return diagnostic information or alternative operations. User-defined exceptions further personalize error handling, which is critical for large-scale applications needing precise control over potential failure points, thus enhancing overall robustness .

Python's main data types are numeric, sequence, mapping, set, boolean, and special. Numeric types (int, float, complex) store numerical values; sequence types (list, tuple, string) store ordered items; mapping types use key-value pairs like dictionaries; set types (set, frozenset) store unique, unordered elements; boolean types store True or False values; and special type NoneType denotes the absence of value .

You might also like