Python B.C.A 4th Sem Score Booster (NEP) For Python
Python B.C.A 4th Sem Score Booster (NEP) For Python
1. Define Python.
Python is a high-level, interpreted, object-oriented programming language that is widely used for
developing various types of applications including web development, data science, artificial intelligence, and
automation.
2. Define variable.
A variable is a named location in memory that stores a value. The value of a variable can be changed
during the execution of a program. Variables can be used to store different types of data, including numbers,
strings, and boolean values.
To create a variable in Python, you simply choose a name for the variable and use the
assignment operator (=) to assign a value to it. Here are some examples:
a=4
y=5.3
3. Name the data types in python with examples.
None type
Numeric type
Bool type
Sequence type
Sets
Mappings
4. What is Indentation?
Indentation refers to spaces that are used in the beginning of a statement. The statements with
same indentation belong to same group called a suite. Python uses Python uses indentation to indicate a block
of code.
6. What is operator?
Operators in Python are symbols or special keywords that perform operations on values
or variables. Python supports a wide range of operators, including
Arithmetic operators
Comparison operators
Logical operators
Bitwise operators
Assignment operators
Ex:
print("Before exit")
exit()
print("After exit")
FEATURES IN PYTHON
There are many features in Python, some of which are discussed below –
1. Easy to code: Python is a high-level programming language. Python is very easy to learn
the language as compared to other languages like C, C#, Java script, Java, etc. It is
very easy to code in python language and anybody can learn python basics in a
few hours or days. It is also a developer-friendly language.
2. Free and Open Source: Python language is freely available at the official website and you can
download it from the given download link below click on the Download
Python keyword. Download Python Since it is open-source, this means that source code is also
available to the public. So you can download it as, use it as well as share it.
4. GUI Programming Support: Graphical User interfaces can be made using a module such as
PyQt5, PyQt4, wxPython, or Tk in python. PyQt5 is the most popular option for creating graphical
apps with Python.
7. Python is Portable language: Python language is also a portable language. For example,
if we have python code for windows and if we want to run this code on other platforms such
as Linux, Unix, and Mac then we do not need to change it, we can run this code on any
platform.
10. Large Standard Library: Python has a large standard library which provides a rich set
of module and functions so you do not have to write your own code for every single thing.
There are many libraries present in python for such as regular expressions, unit-testing, web
browsers, etc.
11. Dynamically Typed Language: Python is a dynamically-typed language. That means the type
(for example- int, double, long, etc.) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.
1. if: The if statement is used to check if a condition is true, and execute a block of code
if the condition is true. Here's an example:
x=5
if x>0:
print("x is positive") #output x is positive
2. if else: The if else statement is used to execute one block of code if a condition is
true, and another block of code if the condition is false. Here's an example:
Ex:
x =10
if x>5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
3. if elif else: elif ladder:
In Python, the elif ladder is a construct that allows you to chain multiple if and else
statements together. The elif statement is short for "else if,” and it allows you to check
for additional conditions after the initial if statement.
Using an elif ladder can be a more efficient way of testing multiple conditions than using
separate if statements for each condition.
Ex:
x=10
if x>20:
print("x is greater than 20")
elif x > 15:
print("x is greater than 15 but less than or equal to 20")
elif x > 10:
2. Data science: Python is a popular language for data science and machine learning, with libraries
such as NumPy, Pandas, and Scikit-learn that provide powerful tools for data analysis and machine
learning.
3. Scientific computing: Python is widely used in scientific computing, with libraries such as SciPy,
Matplotlib, and IPython that provide tools for scientific and engineering calculations.
4. Artificial intelligence and robotics: Python is used in artificial intelligence and robotics, with
libraries such as TensorFlow, Keras, and PyTorch that provide powerful tools for deep learning and
artificial intelligence.
5. Desktop applications: Python can be used to create desktop applications using tools such as PyQt,
wxPython, and PyGTK.
6. Game development: Python can be used in game development, with libraries such as Pygame that
provide tools for creating2D games.
7. Automation: Python can be used for automation tasks, with tools such as Selenium and Beautiful
Soup that provide web scraping and automation capabilities.
8. Scripting: Python is widely used for scripting tasks, with tools such as Fabric and Ansible that provide
automation capabilities for system administration and network management.
Iteration: The repeated execution of some groups of code statements in a program is called
Iteration.
A generic iteration (also called looping) mechanism is depicted in Figure .Like a conditional
statement it begins with a test. If the test evaluates to True, the program executes the loop body once,
and then goes back to reevaluate the test. This process is repeated until the test evaluates to False,
after which control passes to the code following the iteration statement.
While loop: In Python, while loops are used to execute a block of statements repeatedly until a
given condition is satisfied. Then, the expression is checked again and, if it is still true, the body
is executed again. This continues until the expression becomes false.
Syntax:
while(expression):
body of while
flow chart:
For Loops :
A for loop is used to iterate over a sequence that is either a list, tuple, dictionary, or a set. We can
execute a set of statements once for each item in a list, tuple, or dictionary.
Python provides a language mechanism, the for loop, that can be used to simplify programs
containing this kind of iteration.
Syntax:
for variable in sequence:
code block
flow chart:
UNIT –II
Syntax:
Index: Index represents the position number. Index is written using square braces [ ]. By
specifying the position number through an index, we can refer to the individual elements of a string.
For example str[0] refers to the 0th element of the string and str[1] refers to the 1st
element of the string. Thus str[i] can be used to refer to ith element of the string.
Slice: A slice represents a part or piece of a string. The format of slicing is:
Stringname[start: stop: stepsize]
If ‘start’ and ‘stop’ are not specified then slicing is done from 0th to n-1th elements. If stepsize’ is
not written, then is taken to be1.
5 Marks Question
1. What is function? Demonstrate defining and calling user defined function with syntax and
example.
Function is a block of reusable code that performs a specific task. It is defined using the def
keyword, followed by the name of the function and a set of parentheses that may contain parameters or
arguments.
The function block is indented and can contain any number of statements, including return
statements.
Defining Function:
We can define a function using the keyword def followed by function name. After the function name
We should write parentheses ( ) which may contain parameters. Consider the syntax of function as shown
below:
Function definition
def function name(para1, para2 …):
““” function doc string”””
function statements
Example:
def sum(a,b):
“”” This function finds sum of two numbers”””
c=a+b
print(c)
Calling a Function
A function cannot run on its own. It runs only when we call it. So the next step is to call the
function using its name. While calling the function, we should pass the necessary values to the function
in the parentheses as:
sum (10,15)
Here we are calling the sum function and passing two values 10 and 15 to that function. When
this statement is executed, the python interpreter jumps to the function definition and copies the values 10
and 15 into the parameters ‘a’ and ‘b’ respectively. These values are processed in the function body and
result is obtained.
A function that accepts two values and finds their sum.
def sum(a,b):
“”” This function finds sum of two numbers”””
c=a+b
print(‘Sum= “ , c)
# call the function
sum(10, 15)
OUTPUT:
C:\> python fun.py
Sum=25
STRING METHODS:
1. Length of string:
The length of a string represents the number of character’s in a string. To know the length
of a string, we can use len() function. This function gives number of character’s including spaces in
the string.
2. Indexing in python:
Indexing can be used to extract individual characters from a string. In Python, all
indexing is zero-based. [ ]-> read the position of string.
output:
h
output:
yth
output:
CORE PYTHON
6. repeat ( ):
output:
core python core python core python
7. replace():
Replace method used to replace the existing str value into new value.
Str= ‘core python’
Str.replace(“core”,”hi”) print(Str)
output:
hi python
8. concat():
Concat method is used to joining string by using + operator.
Str= ‘hi’ Str1=”python” Str2=Str+Str1 print(Str2)
output:
hi python
3. What are the built exceptions in Python?
In Python, there are many built-in types of exceptions that can be raised during
the execution of a program. Here are some common types of exceptions in Python:
NameError: Raised when a variable or name is not found in the current scope.
ValueError: Raised when a function or operation receives an argument of the correct type but with
an inappropriate value.
KeyError: Raised when a dictionary key is not found in the set of existing keys.
ZeroDivisionError: Raised when the second argument of a division or modulo operation is zero.
4. Explain Exception handling in Python. Write a python program to demonstrate exception handling.
Exception Handling: Exception handling in Python is a mechanism for handling errors that may occur
during program execution. When an error occurs in a program, an exception is raised and if the exception is
The try and except statements are used to implement exception handling in Python.
The try block contains the code that may raise an exception, and
the except block contains the code that should be executed if an exception is raised.
else block: This block contains the code that you want to execute if no exceptions occur within the try
block.
finally block: This block contains the code that you want to execute regardless of whether an exception
occurred or not
You can use try, except, else, and finally blocks in Python to handle exceptions and control the flow of
your program. Here's how you can use each of these blocks:
try block: This block contains the code that you want to execute. If an exception occurs within this block,
the corresponding except block will be executed.
except block: This block contains the code that you want to execute if an exception occurs within the try
block. You can specify the type of exception that you want to catch using the except keyword followed
by the exception type.
else block: This block contains the code that you want to execute if no exceptions occur within the try
block. It is optional and is executed after the try block and before the finally block.
finally block: This block contains the code that you want to execute regardless of whether an exception
occurred or not. It is executed after the try block and any except or else blocks.
Recursive Functions: Recursive functions in Python are functions that call themselves in order to
solve a problem. A recursive function typically has a base case and a recursive case. The base case is a condition
that terminates the recursion, while the recursive case calls the function again with a simplified version of the
original problem.
UNIT-III
1. What is List?
A list is similar to an array that consists of a group of elements or items. Just like an array, a list
can store elements. But, there is one major difference between an array and list. An array can store only
one type of elements whereas a list can store different types of elements. Hence lists are more versatile
and useful than an array. Perhaps lists are the most used data type in Python programs.
3. Define Tuples.
A tuple is a Python sequence which stores a group of elements or items. Tuples are similar to lists
but the main difference is tuples are immutable whereas lists are mutable. Since tuples are immutable,
once we create a tuple we cannot modify its elements. Hence we cannot perform operations like
append(), extend(), insert(), remove(), pop0) and clear() on tuples. Tuples are generally used to store data
which should not be modified and retrieve that data on demand.
4. What is Set?
A set is an unordered collection of unique elements. The set data type is mutable, which means
you can add or remove elements from it. Sets are enclosed in curly braces {} or can be created using the
set() function. Sets do not allow duplicate elements. If you try to add a duplicate element to a set, it will
be ignored
5. What is Dictionaries?
In Python, a dictionary is a built-in data structure that represents a collection of key-
value pairs. Dictionaries are also known as maps.
Dictionaries are used to store key-value pairs. To understand better, think of a phone directory
where hundreds and thousands of names and their corresponding numbers have been added. Now the
constant values here are Name and the Phone Numbers which are called as the keys. And the various
names and phone numbers are the values that have been fed to the keys. If you access the values of the
keys, you will obtain all the names and phone numbers. So that is what a key-value pair is. And in
Python, this structure is stored using Dictionaries. Let us understand this better with an example program.
Operations on Lists: there are several operations that you can perform on lists to
manipulate them in various ways. Here are some common operations on lists:
1. Indexing: You can access an individual item in a list using its index, which starts at 0.
For example, to access the first item in a list:
my_list=[1,2,3]
print(my_list[0]) # Output: 1
2. Slicing: You can create a new list that contains a subset of the items in the original
list by using slicing. Slicing uses a colon to separate the start and end indices, and returns
a new list containing the items from the start index up to, but not including, the end index.
For example:
my_list=[1,2,3,4,5]
print(my_list[1:4]) # Output: [2, 3, 4]
3. Concatenation: You can combine two or more lists into a single list using
concatenation, which uses the + operator. For example:
list1=1[1,2, 3]
list2 =[4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list) # Output: (1, 2, 3, 4, 5, 6]
4. Repetition: You can create a new list that contains multiple copies of the items in the
original list using repetition, which uses the * operator. For example:
my_list=[1,2,3]
repeated_list = my_list * 3
print(repeated_list) # Output: [1,2,3,1,2,3,1,2,3]
5. Length: You can determine the number of items in a list using the len() function. For
example:
my_list=[1, 2, 3]
print(len(my_list)) # Output: 3
6. Membership: You can check if an item is in a list using the in keyword. For example:
my_list=[1, 2, 3]
print(2 in my_list) # Output: True
print(4 in my_list) # Output: False
7. Sorting: You can sort a list in ascending or descending order using the sort() method.
For example:
y_list=[3,1, 2]
my_list.sort() # sorts in ascending order
print(my_list) # Output: [1, 2, 3]
my_list.sort(reverse=True) # sorts in descending order
print(my_list) # Output: [3, 2, 1]
8 Reversing: You can reverse the order of items in a list using the reverse() method.
For example:
my_list=[1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
class Stack:
def __init__(self):
self.stack =[]
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return None
def is_empty(self):
return len(self.stack)
def size(self):
return len(self.stack)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # Output: 3
print(stack.pop()) # Output: 2
print(stack.pop()) # Output: 1
print(stack.pop()) # Output: None (stack is empty)
class Queue:
def __init__(self):
self.queue =[]
def dequeue(self):
if not self.is_empty():
return self.queue.pop(0)
else:
return None
def is_empty(self):
return len(self.queue) == 0
def size(self):
return len(self.queue)
queue = Queue()
queue.enqueue(l)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue()) # Output: 1
print(queue.dequeue()) # Output: 2
print(queue.dequeue()) # Output: 3
print(queue.dequeue()) # Output: None (queue is empty)
1. len() : len(): This function returns the number of items in a list. For example:
my_list=1[1, 2, 3]
print(len(my_list)) # Output: 3
my_tuple =(1, 2, 3)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3]
4. items() method: Returns a list of all the key-value pairs in a dictionary as tuples.
my_dict = {"apple": 2, "banana": 3, "orange": 4}
print(my_dict.items()) # Output: [("apple", 2), ("banana", 3),
("orange", 4)]
5. get() method: Returns the value associated with a key, or a default value if the key is
not found.
VEDANT SCORE BOOSTER Page 19
PYTHON PROGRAMMING
6. pop() method: Removes the key-value pair associated with the specified key and
returns the value.
my_dict = {"apple": 2, "banana": 3, "orange": 4}
print(my_dict.get("apple")) # Output: 2
print(my_dict.get("pear", 0)) # Output: 0
Operations on Sets:
Sets in Python support various operations like union, intersection, difference, and
symmetric difference. Here are some of the most common operations on sets in Python:
1. Union |
2. Intersection &
3. Difference -
4. Symmetric Difference ^
5. Membership Test in
1. Union |:
The union of two sets contains all elements that are in either set. You can
use the |operator or the union() method to perform the union operation.
For example
setl={1,2, 3}
set2 ={3, 4,5}
union_set = setl | set2 # using the | operator
print(union_set) # Output: {1, 2, 3, 4, 5}
union_set = setl.union(set2) # using the union() method
print(union_set) # Output: {1, 2, 3, 4, 5}
2. Intersection & : The intersection of two sets contains only the elements that are
common to both sets. You can use the & operator or the intersection() method to
perform the intersection operation.
For example:
setl={1, 2,3}
set2={3, 4,5}
intersection_set = setl & set2 # using the & operator
print(intersection_set) # Output: {3}
intersection_set = setl.intersection(set2) # using the intersection() method
print(intersection_set) # Output: {3}
Difference - :
The difference between two sets contains only the elements that are in the first set
but not in the second set. You can use the - operator or the difference() method to
perform the difference operation.
For example
setl={1, 2,3}
set2 ={3, 4, 5}
difference_set = setl - set2 # using the - operator
print(difference_set) # Output: {1, 2}
difference_set = setl.difference(set2) # using the difference() method
print(difference_set) # Output: {1, 2}
Symmetric Difference ^ :
The symmetric difference between two sets contains only the elements that are in
either of the sets but not in both. You can use the » operator or the
symmetric_difference() method to perform the symmetric difference operation.
For example:
setl={1,2, 3}
set2 ={3, 4,5}
symmetric_difference_set = setl » set2 # using the » operator
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
symmetric_difference_set = setl.symmetric_difference(set2) # using the
symmetric_difference() method
x in set: Checks if element x is in the set. Returns True if x is in the set, False
otherwise.
x not in set: Checks if element x is not in the set. Returns True if x is not in the set,
False otherwise.
setl == set2: Checks if two sets are equal. Returns True if sets are equal, False
otherwise.
setl < set2: Checks if setl is a proper subset of set2. Returns True if setl is a proper
subset of set2, False otherwise.
setl <= set2: Checks if setl is a subset of set2. Returns True if setl is a subset of set2,
False otherwise.
setl > set2: Checks if setl is a proper superset of set2. Returns True if setl is a proper
superset of set2, False otherwise.
setl >= set2: Checks if setl is a superset of set2. Returns True if setl is a superset of
set2, False otherwise.
UNIT -IV
1. What is - -init( )--?
- -init( )-- : It is a method which is used to initialize the objects of the class
variables. In Python, the method the __init__() simulates the constructor of the class.
This method is called when the class is instantiated. It accepts the self-keyword as a first
argument which allows accessing the attributes or method of the class.
2. What is inheritance? Give syntax to derive child class from parent class.
The process of acquiring properties from one class to another class is called
inheritance. Inheritance is a fundamental concept in object-oriented programming that
allows you to define a new class based on an existing class. The new class (child) inherits
all the properties and methods of the existing (parent) class and can also have its own
properties and methods.
3. Define encapsulation.
Encapsulation: Encapsulation in Python is a mechanism that allows data and
behaviour to be wrapped up together in a single unit, known as a class. The purpose of
encapsulation is to protect the internal state of an object from outside interference and to
provide a controlled way for other objects to interact with it. In Python, encapsulation is
achieved through the use of access modifiers, which limit the visibility of data and
methods within a class.
4.What is file?
File is collection of related data stored in secondary memory.
6. Define polymorphism.
Polymorphism contains two words "poly" and "morphs". Poly means many,
and morph means shape. By polymorphism, we understand that one task can be
performed in different ways. For example – you have a class animal, and all animals
speak. But they speak differently. Here, the "speak" behaviour is polymorphic in a sense
and depends on the animal. So, the abstract "animal" concept does not actually "speak",
but specific animals (like dogs and cats) have a concrete implementation of the action
"speak".
9.Define Constructor.
A constructor is a special type of method (function) which is used to initialize
the instance members of the class. In C++ or Java, the constructor has the same name as
its class, but it treats constructor differently in Python. In Python, the method the
__init__() simulates the constructor of the class. This method is called when the class is
instantiated. It accepts the self-keyword as a first argument which allows accessing the
attributes or method of the class.
Types:
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
Instance of variable
Instance variables are created within the __init__ method of a class, and are
typically prefixed with self. to indicate that they belong to the instance of the class.
Class variable
Class variables, on the other hand, are defined at the class level and are shared by
all instances of the class. They are typically prefixed with the class name to indicate that
they are class variables.
1. Single inheritance:
When a class inherits from a single parent class, it is called single inheritance.
2. Multiple Inheritance:
When a class inherits from more than one parent class, it is called multiple
inheritance.
Multilevel Inheritance:
When a class inherits from a parent class, which in turn inherits from another parent
class, it is called multilevel inheritance.
Multipath Inheritance:
Multipath inheritance in Python is a type of inheritance where a class inherits
from two or more classes that have a common base class. In other words, there is more
than one path from the derived class to the base class.
5 Marks Questions
open() function: This function is used to open a file and returns a file object. It
takes two arguments: the file name (with path, if necessary) and the mode in which
the file is to be opened (e.g. read, write, append, etc.).
Reading a file: You can read the contents of a file using the read() method of the
file object. You can also read one line at a time using the readline() method, or
read all the lines at once using the readlines() method.
Writing to a file: You can write to a file using the write() method of the file
object. If the file does not exist, it will be created. If it already exists, its contents
will be overwritten unless you open it in append mode.
Closing a file: After you are done working with a file, you should close it using
the close () method of the file object. This ensures that all the data that you have
written to the file is saved.
File Operations:
1. Open a file - open()
2. Read or write (perform operation): read(), readline() and write()
3. Close the file: close()
4. Delete aFile
1. Open a File:
Before you can read or write data to a file, you need to open it first. You
can use the built-in open() function to open a file in different modes, such as read-
only, write-only, or read- write. Here's an example of how to open a file in read
mode:
open():
syntax :
open(filename, mode)
Ex:
f = open(“sample.txt”)
or
f = open(“sample.txt”, “r’)
OR
f = open(“sample.txt”, “rt”)
3. Writing to a file:
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file, creates a file if not exists.
"w" - Write - will overwrite any existing content, creates a file if not exists.
“x” — Exclusive Create: - Creates a file if not exists. Failes if file already exists,
VEDANT SCORE BOOSTER Page 28
PYTHON PROGRAMMING
FileExistsError
Closing a File: It is a good practice to always close the file when you are done with it.
Using close() method.
f = open("input.txt", “r’)
str =f.readline()
print(str)
f.close()
Delete a File : To delete a file, you must import the OS module, and run
its os.remove() function:
Benefits of OOP
• We can build the programs from standard working modules that communicate
with one another, rather than having to start writing the code from scratch which leads
to saving of development time and higher productivity,
• OOP language allows to break the program into the bit-sized problems that can be
solved easily (one object at a time).
• The new technology promises greater programmer productivity, better quality of
software and lesser maintenance cost.
• OOP systems can be easily upgraded from small to large systems.
• It is possible that multiple instances of objects co-exist without any interference,
• It is very easy to partition the work in a project based on objects.
• It is possible to map the objects in problem domain to those in the program.
• The principle of data hiding helps the programmer to build secure programs which
cannot be invaded by the code in other parts of the program.
• By using inheritance, we can eliminate redundant code and extend the use of
existing classes.
• Message passing techniques is used for communication between objects which
makes the interface descriptions with external systems much simpler.
• The data-centered design approach enables us to capture more details of model in
an implementable form.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
Types of Inheritance:
Single inheritance
Multiple inheritance
Multilevel inheritance
Multipath inheritance
Hierarchical Inheritance
Example: Write a python program to use addition operator to act on different types
of objects.
OUTPUT:
25
RedFort
[10,20,30,5,15,-10]
UNIT-V
1. What is Frame?
A frame is similar to canvas that represents a rectangular area where some
text or widgets can be displayed. Our root window is in fact a frame.
To create a frame, we can create an object of frame class as:
f=Frame(root,height=400, width=500, bg=”yellow”,cursor=”cross”)
2. What is widget?
A widget is a GUI component that is displayed on the screen and can
perform a task as desired by the user. We create widgets as objects. For
example, a push button is widget that is nothing but an object of Button class.
Similarly, label is a widget that is an object of Label class.
The following are important widgets Python:
Button
Label
Message
Text
Scrollbar
Checkbutton
Radiobutton
Entry
Spinbox
Listbox
Menu
3. Write the uses of any two functions used in GUI layout management?
Functions used in GUI layout management
pack()
grid()
place()
4. What is Cursor?
A cursor object is used to interact with a database. A cursor is created by
a database connection object, and it is used to execute SQL statements and
retrieve data from the database.
commit() method: The commit() method is used to make sure the changes
made to the database are consistent. It basically provides the database confirmation
regarding the changes made by a user or an application in the database.
rollback() method: The rollback() method is used to revert the last changes
made to the database. If a condition arises where one is not satisfied with the
changes made to the database or a database transaction fails, the rollback() method
can be used to retrieve the original data that was changed through the commit()
method.
6. Define database?
7. Define python SQLite?
Python MySQL Connector is a Python driver that helps to integrate Python
and MySQL. This Python MySQL library allows the conversion between
Python and MySQL data types. MySQL Connector API is implemented using
pure Python and does not require any third-party library.
8. Define Numpy?
NumPy is a Python library used for working with arrays. It also has
functions for working in the domain of linear algebra, Fourier transform, and
matrices. NumPy was created in 2005 by Travis Oliphant. It is an open-source
project and you can use it freely.
5 Marks Question
Cursor Object and its methods: A cursor object is used to interact with a
database. A cursor is created by a database connection object, and it is used to
execute SQL statements and retrieve data from the database.
2. cursor() method: This method is used to create a cursor object that can be used
to execute SQL commands. It is called on a connection object and returns a cursor
object.
Here's an example:
# Create a cursor object
¢ = conn.cursor()
4. fetchone() method: This method is used to fetch the next row of a query result
set. It returns a tuple of values or None if there are no more rows to fetch.
Here's an example:
# Fetch the next row
row = c.fetchone()
5. fetchall() method: This method is used to fetch all the rows of a query result set.
It returns a list of tuples of values. Here's an example:
# Fetch all the rows
rows = c.fetchall()
6. commit() method: This method is used to save the changes made to the
database. It is called on a connection object and commits the current transaction.
Here's an example:
# Commit the changes
conn.commit()
7. close() method: This method is used to close the cursor and the connection. It is
called on both the cursor object and the connection object.
Here's an example:
# Close the cursor and the connection
c.close()
conn.close()
import tkinter as tk
root = tk.Tk()
var = tk.StringVar(value="Option 1")
rl = tk.Radiobutton(root, text="Male", variable=var, value="Male")
rl.pack()
r2 = tk.Radiobutton(root, text="Female", variable=var, value="Female")
r2.pack()
root.mainloop()
7. Listbox: This widget is used to display a list of items from which the user
can select one or more.
Ex:
import tkinter as tk
root = tk.Tk ( )
Ib = tk.Listbox(root)
Ib.pack()
Ib.insert(1, "India")
Ib.insert(2, "USA")
Ib.insert(3, "China")
root.mainloop( )
Ex:
import tkinter as tk
root = tk.Tk()
scale = tk.Scale(root, from_=0, to=100, orient=tk. HORIZONTAL)
scale.pack()
root.mainloop( )
Ex:
import tkinter as tk
root = tk.Tk()
menu_bar = tk.Menu(root)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="0Open")
file_menu.add_command(label="Save")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()
1. Line chart: In this example, we first import the pyplot module from the matplotlib
library. We then define the x and y data arrays, which represent the x and y values of the
data points in the line chart.x:
Output:
Output:
Pie chart: In this example, we first import the pyplot module from the matplotlib
library.We then define the sizes and labels lists, which represent the sizes and labels of
the pie chart slices.
Next, we use the plt.pie() function to create a pie chart. The plt.pie() function takes the
sizes and labels lists as arguments and creates a pie chart with the slices labeled with the
labels.
Ex:
import matplotlib.pyplot as plt
# Sample data
sizes = [30, 25, 20, 15, 10]
labels = ['A", 'B','C", 'D", 'E']
# Create pie chart
plt.pie(sizes, labels=labels)
# Add title
plt.title('Pie chart example')
# Show the plot
plt.show()
Output:
Histogram: In this example, we first import the pyplot module from the matplotlib
library and the numpy library for generating random sample data. We then use the
np.random.normal() function to generate a sample of 1000 data points from a normal
distribution with mean 0 and standard deviation 1.
Next, we use the plt.hist() function to create a histogram chart. The plt.hist() function
takes the data array as an argument and creates a histogram chart with 20 bins by default.
Ex:
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
np.random.seed(123)
data = np.random.normal(0, 1, size=1000)
# Create histogram
plt.hist(data, bins=20)
# Add labels and title
plt.xlabel('Data’)
plt.ylabel('Frequency')
plt.title('Histogram example')
# Show the plot
plt.show()
Output:
Selecting Columns: You can select one or more columns from a DataFrame using
indexing. For example, df['column_name'] selects a single column, and
dff['column_1', 'column_2']] selects multiple columns.
Filtering Rows: You can filter rows of a DataFrame using boolean indexing. For
example, df[df['column_name'] > 10] filters rows where the value in column_name is
greater than 10.
Sorting: You can sort a DataFrame by one or more columns using the sort_values()
method. For example, df.sort_values(by='column_name') sorts the DataFrame by
column_name.
Aggregation: You can compute summary statistics of a DataFrame using the agg()
method. For example, df.agg({'column_name": 'mean'}) computes the mean of
column_name.
Grouping: You can group a DataFrame by one or more columns using the groupby()
method. For example, df.groupby(‘column_name').agg({'column_2": 'mean'}) groups
the DataFrame by column_name and computes the mean of column_2 for each group.
Joining: You can join two or more DataFrames using the merge() method. For
example, pd.merge(df1, df2, on="column_name') joins df1 and df2 on column_name.
Reshaping: You can reshape a DataFrame using the pivot() method. For example,
df.pivot(index="column_1', columns='column_2', values='column_3') pivots the
DataFrame so that column_1 becomes the index, column_2 becomes the columns, and
column_3 becomes the values.