SET-I
ANS.1.
A data type is a term used in Python that defines the type of variable stored in a program.
Data types also define how variables are treated and how they can be worked with There are
many different data types included with Python, some of which are found in the following
graphic.
1. Numeric Data Types
➢ Numeric data types refer to the types of numbers represented by variables in Python.
➢ Python supports three numeric data types: Integer, Float and Complex.
Integer (int)
➢ Integers represent whole number values including positive, negative and zero values.
➢ Examples: 10, -5, 0
➢ Integers have no limitations on the precision of values represented by integers and are
commonly used for counting and performing arithmetic calculations.
Float (float)
➢ The Float data type represents decimal or fractional number values.
➢ Examples: 3.14, -0.5
➢ Float data types are frequently used in scientific and engineering calculations where
accuracy is essential.
Complex (complex)
➢ Complex numbers can be broken down into their real part and imaginary part.
➢ Complex numbers are written in the form a + xj where "j" is the imaginary unit.
➢ Example: 2 + 6j
➢ Complex data types are typically used for scientific and mathematical calculations.
2. Dictionary Data Type
➢ A dictionary is a data type that associates a value to a key.
➢ Every key has a unique value associated with it, allowing the value to be retrieved
using the key.
➢ Dictionaries can have their values modified after the dictionary has been created.
➢ All keys in the dictionary must be immutable data types, like integers and strings.
➢ Example: student = {"name": "Amit", "age": 20}
➢ Dictionaries are commonly used in various areas including database's, configuration
files, and as a representation of structured data.
3. Boolean Data Type
➢ The boolean data type contains the logical value of true or false.
➢ The boolean data type only contains two possible values: true or false.
➢ You will typically see the boolean values being used in a conditional statement or in a
loop.
➢ Example:
➢ result = 6 > 2 # true
4. Set Data Type
The set data type is an unordered data collection that contains only one copy of each element.
You cannot have duplicate values in a set.
A set is a mutable data type and has very well-defined uses in mathematical operations (union
and intersection).
Example:
numbers = {5, 6, 7}
5. Sequence Data Types
The sequence data type represents an ordered data collection.
In Python, three data types are built-in for sequence data types: String, List, and Tuple.
String (str)
o Strings are a sequence of characters and represent text.
o Strings are an immutable data type.
o Example: "C Programming"
List (list)
o Lists are an ordered collection of elements that can be changed after they are created.
o The elements stored in a list can be of any data type.
o Example: [1, "apple", 3.5]
Tuple (tuple)
o Tuples are similar to lists, but they cannot be changed after they have been created.
o Operated when data must not be adjusted.
o Example: (50, 60, 70)
ANS.2.
Local Variables:
• Defined inside a function (within that function's block).
• Scope limited to the function/block where they are created (i.e., they can only be accessed
within that function/block).
• Created at the time the function is called (execution starts) and destroyed immediately after
the function has finished executing (therefore, their lifespan is very short).
• If not explicitly initialized, local variables will typically contain "garbage" values.
• Local variables are efficient in terms of memory usage because they are local to the calling
function and do not affect any other part of your program.
• Because local variables are restricted to a single procedure/function, they cannot be
accessed directly by any other procedure(s)/function(s).
Global Variables:
• Declared before any functions, typically at the very beginning of your program (before all
the functions).
• Scope is entire program so that they can be accessed and modified by any function within
that program.
• A global variable will exist for the entire time that the program is running.
• If not explicitly assigned a value, global variables will automatically be assigned a zero
value (or None depending on what language you are coding in).
• Global variables make it easy to share information/lots of information between functions;
however, they can make debugging and maintaining code more complicated because global
variables may be changed by any number of other functions in the program.
Key Differences
Feature Local Variable Global Variable
Declaration Inside a function/block Outside all functions
Scope Limited to the defining Entire Program
block
Lifetime Function performance time Entirety Program runtime
Defaulting Value Garbage/Indefinite Zero/None
Data Sharing Not possible immediately Possible amongst function
Memory Collected on Stack Kept in fixed data segment
Using Keyword Global with Example
When you define an variable within a function, Python regards as a completely new local
variable and "shadows" (or obscures) any existing global variable of the same name. In order
to change a variable that is declared as global from within a function, it is necessary to
indicate that you are using the global version of the variable by using the global keyword.
This keyword tells the interpreter to locate this variable in the global scope, and not create a
new local variable.
Example
# Global variable
balance = 5000
def update_balance(amount):
global balance
balance += amount # This replaces the global 'balance'
print(f"Updated balance inside function: {balance}")
def check_balance():
print(f"Current balance: {balance}")
check_balance() # Output: Current balance: 5000
update_balance(500) # Output: Updated balance inside function: 5500
check_balance() # Output: Current balance: 5500
The balance within update_balance() would be a local variable in the absence of the global
keyword, and the global balance would not change.
In conclusion, to guarantee modularity and security, select local variables for transient,
function-specific data. When modifying global variables from within functions, use the
global keyword carefully. Use global variables sparingly for data that actually needs to be
shared program-wide. Writing clear, effective, and maintainable code requires striking this
balance.
ANS.3.
Python's list is a construct allowing an easy way to aggregate and manipulate a collection of
similar items. Lists are considered one of Python's built-in data types; lists encapsulate
multiple data items into one variable, thereby providing a mechanism for representing groups
of related data efficiently, as opposed to using multiple variables. An example of a list of
integers could be [1, 2, 3, 4, 5]. In contrast to arrays in some other languages, Lists have a
fixed length, with fixed indexes (position), and the first index always starts at 0; hence if a list
has three integers, the integer in the first index would be the first integer.
The element within a list maintains an ordered sequence. Each element in the list has a
specific index (position), and the index always starts at 0 for the first element within the list.
Additionally, lists support negative indexing. -1 represents the last item in the list.
Another significant characteristic of lists is that lists are mutable (i.e. they can be changed or
modified). Therefore, we can insert (add), update, or delete items in the list after they have
already been created. In addition, lists allow duplicate values (the same values), and they can
be homogeneous (i.e. all elements of the same data type) or heterogeneous (i.e., different data
types) (e.g., integers, strings, and decimal values)
Deletion in a List
The process of removing an element from a list which will alter the size and content of the
list is referred to as Deletion. Deletion is often useful when certain items are no longer
needed; there are two primary methods for deleting elements within a Python List;
specifically by (1) Elimination through Value, and by (2) Deletion through Index Value. The
two most widely used built-in delete functions are remove() and pop().
1. remove() Method – Eliminate by Value
The remove() method will delete a List item based upon its value. It will locate and eliminate
only the first (1st) occurrence of the identified value from the List.
For Example:
List1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[Link](10) => Will remove the first (1st) occurrence of the value of 10.
[Link](1) => Will remove the first (1st) occurrence of the value of 1.
The technique described utilizes remove() and pop() to delete elements from a specified
index and on a range. for example 10 and 1 have been removed from the list using the
remove() method. As the, remove() allows the user to specify which elements should be
removed, as well as all of the elements that fall within a specific range of index numbers.
2. The pop() method (Deletion by Index)
The pop() function returns the value that was removed and eliminates an element based on its
index position.
As an example:
[Link]()
[Link](4)
pop() without an argument removes the final element of the list, whereas pop(4) removes the
fifth element (4 is an index), as indicated in the pop() functions as a removement tool
allowing the user to remove elements either at the end of a list or at a given index.
SET-II
ANS.4.
a) Break, Continue, and Pass Statements
These statements are used to control the flow of loops.
Break: Break is used when we need to completely exit a loop.
• Use when you want your looping to cease performing immediately upon a successful
completion of the condition.
Example:
If you are printing counts from 1 to 10 but want to stop at 5.
for i in range(1, 11):
if i == 5:
break
print(i)
# This will print only 1, 2, 3, 4
Continue: This skips the current iteration and proceeds to the next step in the loop.
• Use when you want to bypass certain statements for specific values but still continue
the looping.
• Example: If you want to print counts from 1 to 5 but want to skip to 3.
for i in range(1, 6):
if i == 3:
continue
print(i)
# This will print 1, 2, 4, 5 (3 skipped)
Pass: This is a "null" statement. Pass is used when we syntactically need a block but don't
want to write any code there (want to leave it blank for the future).
• Use primarily when you're writing the structure of your code, which you plan to
complete later.
Example
if x > 10:
pass
# Nothing to do here right now, I'll write the code later
b). In Object-Oriented programming for Python, each method of instance has a standard first
argument, which is "self". This is the instance of the class for that instance, as opposed to
class-wide (all-instances). "Self" within an instance method provides access to the specific
objects associated with it.
• "Automatic Binding". Whenever an instance is called as a method object (via the dot
operator), "self" (a keyword argument) is automatically supplied to that method from
the instance.
• A method through "self" can both access the attributes of the instance the method is
associated with and change those attributes, and can also call other methods on the
same instance.
• "Self" is not an actual Python keyword, it's just a naming convention used in the
Python language. While taking a different name for "self" is technically allowed, it is
highly discouraged, as it's an integral part of understanding and written, and therefore
clean coding.
The concept of "self" is an integral part of Object Oriented programming (OOP) to
differentiate between an instance of an instantiated class and an instance method. For an
instance, instance methods can perform a distinct function at the same time can cause the
methods to behave like a static function.
ANS.5.
Exception Handling
An exception can be defined as an irregular occurrence that interrupts a program's course of
completion. The statement above summarizes the definition of an exception and examples of
situations that can give rise to exceptions in programming languages.
In Python when an exception occurs it will terminate execution with an output detailing the
cause of the exception. This is a problematic feature in many commercial applications as it
creates an unpleasant experience for customers and users. In order to prevent program
termination when an exception is raised, the Python programming language provides a
valuable functionality known as Exception Handling.
Exception Handling in Python enables the programmer to manage the way that program
errors occur. This is accomplished primarily by means of the try/ except blocks of code.
try–except Mechanism
o The try block contains the code which might produce an exception during execution
of the program.
o The except block contains the code which will execute if an exception is produced.
o When a try block produces an error, rather than producing an exception and
terminating the program, Python will continue running the program and, if necessary,
execute code from the except block.
o This facility of handling exceptions enhances the reliability and usability of programs
written in Python.
User-Defined Exceptions in Python
Python supports the ability to define user-defined exceptions to allow the programmer to set
some defined expectations in their own code as well as provide an option to do something
manual if those expectations aren't met.
To define a custom exception in Python, you create a new class (which is the custom
exception) that inherits from the base Exception class. Once defined, you use the keyword
raise to throw that exception when you need it.
The basic steps to create a user-defined exception would be:
1. Define the custom exception class – it should inherit from Exception
2. Raise it when necessary
3. Handle it using the try-except construct.
Example Code:
class InvalidAgeError(Exception):
pass
try:
age = int(input("Enter your age: "))
if age < 28:
raise InvalidAgeError("Age must be 28 or above")
print("Access granted")
except InvalidAgeError as e:
print(e)
Explanation
The program raises an exception when the user's age is less than 28. This exception will be
caught by the catch block so that a more meaningful message is displayed rather than
crashing.
Conclusion
Exception Handling is one of the most important components in Python because Exception
handling protects the Python user from unexpected crashes and enhances the user's
experience with programs written in Python. The use of try-except blocks and user-defined
exceptions allows developers to write cleaner, safer, and more reliable code. In addition,
exception handling separates the error handling logic from the main logic, making it easier to
debug and maintain.
ANS.6.
The language used by Structured Query Language (SQL) to Communicate to Database(s)
is called the SQL. SQL is used to Create, Modify, Retrieve and Control the Data stored in the
Database. The structure with which you Create, Modify, Retrieve, and Control your data is
through the Various Commands in SQL, which are grouped into four Parts. These Four Parts
are called DDL, DML, DCL, and TCL.
1. DDL (Data Definition Language)
DDL Commands are used to Define the Tables and the Data contained in the Database and
Structure of the [Link] (and create) and manage the Table Structure.
• Create: The Command used to Create (new) Database(s) and/or Table(s), for example,
a Student Table.
• Alter: The Command to Change the existing Table Structure by adding or deleting
Columns or changing Column Data Type(s).
• Drop: The Command to Remove (delete) a Table or Database and all Data associated
with it permanently.
• Truncate: The Command to remove all Data from a Table, while maintaining the
Structure of the Table. The Main Difference between DROP and TRUNCATE is.
• Rename: The Command for changing the Names of Tables or Databases.
DDL Commands are mainly used during Database Design and Structural Changes.
2) Data Manipulation Language
DML commands allow you to manipulate data stored in your database(s) by inserting,
updating, deleting or retrieving it using SQL statements.
The most common types of DML statements include:
• INSERT: Add new records into your table
• UPDATE: Modify existing records within your table(s)
• DELETE: Remove specific records from your table
• SELECT: Retrieve data from one or more of your tables
DML commands can be reversed (rolled back) should you need to undo the changes made to
the data using those commands.
3) Data Control Language
DCL commands are the commands used to control how and who has access to your database
system and its' data. DCL is very helpful in keeping your database secure by controlling user
access by giving or denying access based on the permissions that you have specified.
Common DCL commands include:
• GRANT: Grants specific privileges to a user or group of users.
• REVOKE: Revokes previously granted privileges from a user or group of users.
DCL is used by Database Administrators to manage User Roles and Permissions.
4. TCL - Transaction Control Language
Database transactions are managed with TCL commands. A transaction is a sequence of SQL
commands that act as a single operation.
The primary types of TCL Commands include:
• COMMIT - When a COMMIT command is issued, the transaction's changes will be
saved permanently.
• ROLLBACK - A ROLLBACK command reverses any changes made during the
transaction.
• SAVEPOINT - A SAVEPOINT creates a spot in the transaction that can be rolled back
to.
TCL commands help maintain the integrity and consistency of your data, particularly when
there are multiple users.
Conclusion
DDL establishes the structure of the database, DML provides manipulation of the data, DCL
establishes the rules for access to the data, and TCL is used to control the transactions. When
you combine the four SQL Command Types together you get full control of creating a
Database, Securing it, Manipulating it's Data and Controlling Transactions, which is why
SQL is such an extremely powerful Database Language.