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

Python B.C.A 4th Sem Score Booster (NEP) For Python

The document provides an overview of Python programming, covering its definition, features, data types, and key concepts such as variables, operators, and control flow statements. It also discusses exception handling, string manipulation, and built-in functions, along with practical examples. Additionally, it highlights various applications of Python in fields like web development, data science, and automation.

Uploaded by

mahanteshdhari69
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 views46 pages

Python B.C.A 4th Sem Score Booster (NEP) For Python

The document provides an overview of Python programming, covering its definition, features, data types, and key concepts such as variables, operators, and control flow statements. It also discusses exception handling, string manipulation, and built-in functions, along with practical examples. Additionally, it highlights various applications of Python in fields like web development, data science, and automation.

Uploaded by

mahanteshdhari69
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
You are on page 1/ 46

PYTHON PROGRAMMING

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.

5. What is range data type?


The range data type represents a sequence of numbers. The numbers in the range are not
modifiable. Range is used for repeating a for loop for a specific number of times.
To create a range of numbers, we can simply write:
R=range(10)
It creates with the numbers starting from 0 to 9.

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

VEDANT SCORE BOOSTER Page 1


PYTHON PROGRAMMING

7. What is Exit () function?


The exit() function is used to immediately terminate the Python interpreter. It
takes an optional integer argument that can be used to specify an exit status.

Ex:
print("Before exit")
exit()
print("After exit")

5 Marks Question and Answers


1. Explain features of python.

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.

3. Object-Oriented Language: One of the key features of python is Object-Oriented programming.


Python supports object-oriented language and concepts of classes, objects
encapsulation, etc.

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.

5. High-Level Language: Python is a high-level language. When we write programs in python, we


do not need to remember the system architecture, nor do we need to manage the
memory.
6. Extensible feature: Python is a Extensible language. We can write us some Python code into C or
C++ language and also we can compile that code in C/C++ language.

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.

VEDANT SCORE BOOSTER Page 2


PYTHON PROGRAMMING
8. Python is Integrated language: Python is also an Integrated language because we can
easily integrated python with other languages like c, c++, etc.

9. Interpreted Language: Python is an Interpreted Language because Python code is


executed line by line at a time. like other languages C, C++, Java, etc. there is no need to
compile python code this makes it easier to debug our code. The source code of python is
converted into an immediate form called byte code.

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.

2. Explain various conditional statements with syntax and example.

Branching statements/Control Flow Statements/conditional statements

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:

VEDANT SCORE BOOSTER Page 3


PYTHON PROGRAMMING
print("x is greater than 10 but less than or equal to 15")
else:
print("x is less than or equal to 10")

3. What are the applications of Python?


Applications of Python:
1. Web development: Python is widely used for web development, with popular web frameworks such as
Django and Flask that allow developers to create dynamic and scalable web applications.

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.

4. Explain Iteration. Give example program

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.

VEDANT SCORE BOOSTER Page 4


PYTHON PROGRAMMING

There come two main looping statements:


While loop
For loop

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:

VEDANT SCORE BOOSTER Page 5


PYTHON PROGRAMMING

UNIT –II

1. What is exception? Mention built-in exceptions in python.

An exception can be defined as an unusual condition in a program resulting in the interruption in


the flow of the program. Whenever an exception occurs, the program stops the execution, and thus the
further code is not executed. Therefore, an exception is the run-time errors that are unable to handle to
Python script. An exception is a Python object that represents an error.

Common Exceptions are:

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It maybe local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached ,and yet operations are
being performed

2. What is exception handling?


Exception handling is a mechanism in Python that allows you to catch and handle errors that occur
during program execution. When an error occurs, an exception is raised, and if the exception is not
handled, the program will terminate with an error message and program terminates abnormally.

3. What is the use of return statement in functions?


Return statement is used to exit a function and return a value or expression to the caller. The
return statement can be used in any function, regardless of its parameters or body. The return statement
can also be used to return multiple values from a function, using tuples or other data structures.

4. Define string? Give syntax.


Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes. The computer does not understand the characters internally, it stores manipulated character
as the combination of the 0's and 1's. It is a sequence of characters. It is a data type that is used to
represent textual data, such as words or sentences.

Syntax:

str = "Hi Python"

5. What is indexing & slicing?

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.

VEDANT SCORE BOOSTER Page 6


PYTHON PROGRAMMING

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.

6. What are escape sequences? List them.


Escape sequences are used to represent special characters in a string. They are preceded by a
backslash (\). Here are some common escape sequences:

7. What is the use of raise statement?


The Raise keyword raises a specific exception when a condition is met or the code encounters
an error. The exception raised by the program may either be an exception instance or an exception class.
When you use the raise keyword, you can define what kind of error the machine should raise for a
particular exception.

8. What is Assert statement in python? Give syntax.


The assert statement is useful to ensure that a given condition is true. If it is not true, it raises
Assertion Error.
The syntax is as follows:
Assert condition, message
If the condition is False, then the exception by the name Assertion Error is raised along with the
‘message’ written in the assert statement. If ‘message ‘ is not given in the assert statement and the
condition is False, then also Assertion Error is raised without message.

9. What is error? What are the different types of error in Python?


An error is an exceptional event or a mistake in a program that occurs during program
execution and prevents the program from running as intended. Errors can occur for a variety of
reasons, such as syntax errors, runtime errors, and logical errors.
Types of Errors:
1. Syntax Error
2. Runtime Error
3. Logical Error

VEDANT SCORE BOOSTER Page 7


PYTHON PROGRAMMING

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

VEDANT SCORE BOOSTER Page 8


PYTHON PROGRAMMING

2. Explain any 5 string built-in functions with examples.

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.

Str= ‘core python’ n=len(Str) print(n)


output:
11

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.

Str= ‘core python’ Str1=Str[9] print(Str1)

output:
h

3. Slicing the string:


Slicing is used to extract substrings of arbitrary length. If s is a string, the expression
s[start:end] denotes the substring of s that starts at index start and ends at index end-1.

Str= ‘core python’ Str1=Str[6:9] print(Str1)

output:
yth

4. lower ( ):or small letter.


lower method used to convert entire given string into lowercase

Str= ‘CoRE python’ n=Str.lower() print(n)


output: core python

5. upper ( ):or capital letter.


Upper method used to convert entire given string into uppercase

Str= ‘CoRE python’ n=Str.upper() print(n)

output:
CORE PYTHON
6. repeat ( ):

VEDANT SCORE BOOSTER Page 9


PYTHON PROGRAMMING
It is used to repeat the value of given string by using * operator with integer and string.

Str= ‘core python’ Str1=Str*3 print(Str1)

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:

 SyntaxError: Raised when there is a syntax error in the code.

 TypeError: Raised when an operation or function is applied to an object of in appropriate type.

 NameError: Raised when a variable or name is not found in the current scope.

 AttributeError: Raised when an attribute reference or assignment fails.

 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.

 IndexError: Raised when an index is not found in a sequence or list.

 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

VEDANT SCORE BOOSTER Page 10


PYTHON PROGRAMMING
not handled, the program will terminate with an error message.
The basic idea behind exception handling is to try to execute a piece of code that may raise an
exception, and then catch and handle the exception if it is raised.

Exception Handling using try, except and finally:

 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.

VEDANT SCORE BOOSTER Page 11


PYTHON PROGRAMMING

5. What is recursion? Explain with a program.

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.

VEDANT SCORE BOOSTER Page 12


PYTHON PROGRAMMING

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.

2. What is sequence data type?


A sequence is a data type that represents a group of elements. The purpose of any sequence is to
store and process a group of elements. In Python, strings, lists, tuples and dictionaries are very important
sequence data types. All sequences allow some common operations like indexing and slicing.

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.

VEDANT SCORE BOOSTER Page 13


PYTHON PROGRAMMING

6. What are the Operations of List?

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.

VEDANT SCORE BOOSTER Page 14


PYTHON PROGRAMMING

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]

7. Write a program to implement stack using List.

class Stack:
def __init__(self):
self.stack =[]

def push(self, element):


self.stack.append(element)

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)

VEDANT SCORE BOOSTER Page 15


PYTHON PROGRAMMING

8. Write a program to implement Queue using List.

class Queue:
def __init__(self):
self.queue =[]

def enqueue(self, element):


self.queue.append(element)

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)

VEDANT SCORE BOOSTER Page 16


PYTHON PROGRAMMING

9. Explain any 5 built in function of List with example

Built-in Functions on Lists:

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

2. max() - Returns the maximum value in the list.


my_list=[1,3,2]
print(max(my_list)) # Output: 3
my_list = ['apple’, 'banana’, 'cherry']
print(max(my_list)) # Output: 'cherry'

3. min() - Returns the minimum value in the list.


my_list=[1,3,2]
print(min(my_list)) # Output: 1
my_list = ['apple’, 'banana’, 'cherry']
print(min(my_list)) # Output: 'apple’
4. sum() - Returns the sum of all elements in the list.
my_list=[1,2,3]
print(sum(my_list)) # Output: 6

5. sorted() - Returns a sorted version of the list in ascending order.


my_list=(3,1,2]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 3]
my_list = ['banana’, 'cherry', 'apple']
sorted_list = sorted(my_list)
print(sorted_list) # Output: ['apple', 'banana’, 'cherry']

6. reversed() - Returns a reverse iterator of the list.


my_list=[1, 2, 3]
reversed_list = list(reversed(my_list))
print(reversed_list) # Output: 3, 2, 1]

7. list() - Converts a sequence (tuple, string, etc.) into a list.

VEDANT SCORE BOOSTER Page 17


PYTHON PROGRAMMING

my_tuple =(1, 2, 3)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3]

8. count() - Returns the number of occurrences of a specified element in the list.


my_list=[1,2,3,4,5,1]
count = my_list.count(1)
print(count) # Output: 2

10. Explain any 5 built in function of tuple with example.

Built-in Functions on Tuples;

1. len(): Returns the number of elements in a tuple.


my_tuple =(1,2,3,4,5)
print(len(my_tuple)) # prints 5

2. max(): Returns the largest element in a tuple.


my_tuple=(1, 2,3, 4,5)
print(max(my_tuple)) # prints 5

3 min(): Returns the smallest element in a tuple.


my_tuple=(1, 2,3, 4,5)
print(min(my_tuple)) # prints 1
4.sum(): Returns the sum of all elements in a tuple (only works with
numeric types).
my_tuple =(1, 2, 3,4,5)
print(sum(my_tuple)) # prints 15
5. sorted(): Returns a sorted list of the elements in a tuple.
my_tuple =(5,3,1,4,2)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # prints [1, 2, 3, 4, 5]

VEDANT SCORE BOOSTER Page 18


PYTHON PROGRAMMING

6. any(): Returns True if at least one element in a tuple evaluates to True.


my_tuple = (0, False, None, ", [], {})
print(any(my_tuple)) # prints False
my_tuple2 = (0, False, None, ", [], {}, 1)
print(any(my_tuple2)) # prints True

7. all(): Returns True if all elements in a tuple evaluate to True.


my_tuple = (1, True, 'hello’, [1, 2, 3])
print(all(my_tuple)) # prints True
my_tuple2 = (1, True, 'hello’, [1, 2, 3], False)
print(all(my_tuple2)) # prints False

11. Explain any 5 built in function of Dictionaries.

Built-in Functions on Dictionaries:

1. len() function: Returns the number of key-value pairs in a dictionary.


my_dict = {"apple": 2, "banana": 3, "orange": 4}
print(len(my_dict)) # Output: 3

2. keys() method: Returns a list of all the keys in a dictionary.


my_dict = {"apple": 2, "banana": 3, "orange": 4}
print(my_dict.keys()) # Output: ["apple", "banana", "orange"]

3. values() method: Returns a list of all the values in a dictionary.


my_dict = {"apple": 2, "banana": 3, "orange": 4}
print(my_dict.values()) # Output: [2, 3, 4]

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

my_dict = {"apple": 2, "banana": 3, "orange": 4}


print(my_dict.get("apple")) # Output: 2
print(my_dict.get("pear", 0)) # Output: 0

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

12. What are the Operations of Set?

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}

VEDANT SCORE BOOSTER Page 20


PYTHON PROGRAMMING

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

VEDANT SCORE BOOSTER Page 21


PYTHON PROGRAMMING

print(symmetric_difference_set) # Output: {1, 2, 4, 5}

Membership Test (in) :


Membership Test: You can test if an element is a member of a set using the in
operator.
For example:
setl={1, 2,3}
print(2 in setl) # Output: True
print(4 in setl) # Output: False

13. Explain any 5 built in function of Sets


len(set): Returns the number of elements in the set.

set() or {}: Creates an empty set.

set(iterable): Creates a set from an iterable (list, tuple, string, etc.).

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.

VEDANT SCORE BOOSTER Page 22


PYTHON PROGRAMMING

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.

5. Define 2 types of files.


1. Text file
2. Binary file

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".

VEDANT SCORE BOOSTER Page 23


PYTHON PROGRAMMING

7. Define class with syntax.


A class is a blueprint for creating objects that have specific attributes and
methods. Class is a collection of data members (instance variables + constructors +
methods). Class creation syntax: In Python, you can create a class using the class
keyword followed by the name of the class and a colon. The body of the class is indented
and contains attributes and methods.

8. Define an object with its syntax.


The object is an entity that has state and behaviour. It may be any real-world
object like the mouse, keyboard, chair, table, pen, etc. Everything in Python is an object,
and almost everything has attributes and methods. All functions have a built-in attribute
__doc__, which returns the docstring defined in the function source code.

Object-oriented programming (OOP) is a programming paradigm that is based


on the concept of objects are instances of a class, and they can have different values for
their attributes while sharing the same methods. Object is anything that has physical
existence, state and behaviour. Object creation
syntax:
obj = Class Name(val l, val 2)

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.

10.Define Inheritance in python. list types of it.


The process of acquiring properties from one class to another class is called
Inheritance. It is a fundamental concept in object-oriented programming that allows you
to define a new class based on an existing class.

Types:
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance

VEDANT SCORE BOOSTER Page 24


PYTHON PROGRAMMING

11. What are file modes, list.

Modes of access of files:

12. Write the syntax to create class & objects.


class ClassName:
obj = ClassName(Val l, Val2)

13. Define self variable?


‘self’ is a default variable that contains the memory address of the instance of the
current class so we can use ‘self’ to refer to all the instance variables and instance
methods.

14. Explain types of constructor methods.


Types of constructor
1. Default constructor
2. Parameterized constructor

15. What are instance variables and class variables?

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.

VEDANT SCORE BOOSTER Page 25


PYTHON PROGRAMMING

16. Define single & multiple inheritance

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.

17. Define multilevel & multipath 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.

18.What is operator overloading?


Operator Overloading means giving extended meaning beyond their predefined
operational meaning. For example operator + is used to add two integers as well as join
two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int
class and str class. You might have noticed that the same built-in operator or function
shows different behaviour for objects of different classes, this is called Operator
Overloading.

19. Define private instance variable.


In Python, private instance variables are variables that are intended to be used
within the class and not directly accessed or modified from outside the class.
20. What is method overloading?
If a method is written such that it can perform more than one task,it is called method
overloading.
For example:
Sum(10,15)
Sum(10,15,20)

VEDANT SCORE BOOSTER Page 26


PYTHON PROGRAMMING

21. What is method Overriding?


When there is a method in the super class, writing the same method in the sub class
so that it replaces the super class method is called method overriding.

22. What is Method Resolution Order(MRO)?


In the multiple inheritance scenario, any specified attribute or method is searched
first in the current class. If not found , the search continues into parent classes in depth
first,left to right fashion without searching the same class twice. Searching in this way is
called Method Resolution Order(MRO.)

5 Marks Questions

1. What is File Handling? Explain the functions of file handling.

File Handling: File handling is the process of creating, manipulating, and


reading files in a computer program. In Python, you can perform file handling
operations using built-in functions and modules.

Files: File is a collection of related data stored on a secondary storage.


File extensions: .txt, .docx, .pdf, .c, .cpp etc
Python has several functions for creating, reading, updating, and deleting files.

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.

VEDANT SCORE BOOSTER Page 27


PYTHON PROGRAMMING

2. What are the file operations? Explain indetail.

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”)

2. Reading from a File:


read(): This method reads the entire contents of a file as a string. Here's an
example:
Ex:
file = open(‘example.txt’, 'r')
contents = file.read()
print(contents)

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

write(): This method writes a string to a file. Here's an example:


Ex:
file = open('example.txt', 'w')
file.write('This is some text.")

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:

3. What is constructor? Explain with an example.

Constructor Method: The constructor method is a special method that is


called when an object is created from a class. The constructor method is named
__init__ and it is used to initialize the attributes of the object.

The constructor method in Python has the following features:


 It is a special method that is called automatically when an object is created from a
class.
 It has the name __init__ and takes at least one parameter (self) which refers to the
object being created.
 It is used to initialize the attributes of the object.
 It can take any number of parameters after self to initialize the attributes of the
object.
 It can also contain default parameter values for its arguments.
 It can perform any necessary setup for the object before it is used.

VEDANT SCORE BOOSTER Page 29


PYTHON PROGRAMMING

4. Write the advantages of OOPs.

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.

VEDANT SCORE BOOSTER Page 30


PYTHON PROGRAMMING

5. What is Inheritance? Explain types of inheritance with an example.

Inheritance: the process of acquiring properties from one class to another


class. 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. In Python, you can create a new class that
inherits from an existing class by specifying the existing class in parentheses after
the new class name, like this:

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

VEDANT SCORE BOOSTER Page 31


PYTHON PROGRAMMING

6. What is operator overloading? Explain with an example.

Operator Overloading means giving extended meaning beyond their


predefined operational meaning. For example operator + is used to add two
integers as well as join two strings and merge two lists. It is achievable because ‘+’
operator is overloaded by int class and str class. You might have noticed that the
same built-in operator or function shows different behaviour for objects of
different classes, this is called Operator Overloading.

Example: Write a python program to use addition operator to act on different types
of objects.

# overloading the + operator


#using + on integers to add them
print(10+15)
# using + on strings to concatenate them
S1=”Red”
S2=”Fort”
print(S1+S2)
# using + on lists to make a single list
a= [10,20,30]
b=[5,15,-10]
print(a+b)

OUTPUT:
25
RedFort
[10,20,30,5,15,-10]

7. What are the features of Object Programming System?


There are five important features related to Object Oriented Programming System.
They are:
1. Classes and objects
2. Encapsulation
3. Abstraction
4. Inheritance
5. Polymorphism

VEDANT SCORE BOOSTER Page 32


PYTHON PROGRAMMING

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.

VEDANT SCORE BOOSTER Page 33


PYTHON PROGRAMMING

5. Define commit and rollback?

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.

9. List any two features of Numpy?


Array-oriented computing - NumPy provides an easy-to-use interface for
performing array-oriented computing tasks. This makes it easy to perform
complex mathematical operations on arrays of data.

Broadcasting - NumPy allows you to perform operations on arrays of different


shapes and sizes. This is called broadcasting and it can save you a lot of time
and effort when working with large datasets.

VEDANT SCORE BOOSTER Page 34


PYTHON PROGRAMMING

10. Define pandas?


Pandas is a Python library used for data manipulation and analysis. It
provides data structures for efficiently storing and manipulating large datasets
and tools for working with structured data.

11. Name the types of charts used in matplotlib pyplot?


a. Line Chart
b. Bar Chart
c. Pie Chart
d. Histogram

5 Marks Question

1. Write the steps to connect database in python.

1. connect: connect() method: This method is used to create a connection to an


SQlite database. It takes a single argument - the name of the database file - and
returns a connection object that can be used to execute SQL commands.
If the database file does not exist, it will be created automatically.
Here's an example:
import sqglite3
# Create a connection to the database
conn = sqlite3.connect('example.db')

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()

VEDANT SCORE BOOSTER Page 35


PYTHON PROGRAMMING

3. execute() method: This method is used to execute an SQL command. It takes a


single argument - the SQL command - and returns a cursor object that can be used
to fetch the results.
Here's an example:
# Execute a query
c.execute('CREATE TABLE person (id integer, name text)')

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()

VEDANT SCORE BOOSTER Page 36


PYTHON PROGRAMMING

2. Write a python to insert and display the employee in database.


import sqlite3
# create connection to a SQLite database
conn = sqlite3.connect('test.db')
# create a cursor object
cursor = conn.cursor()
# create a table
cursor.execute("CREATE TABLE employee (id INTEGER,name TEXT)")
# insert a record into table
cursor.execute("INSERT INTO employee(id,name) VALUES (101, 'Ravi')")
cursor.execute("INSERT INTO employee(id,name) VALUES (102, 'Ravishankar')")
cursor.execute("INSERT INTO employee(id,name) VALUES (103, 'Ramesh')")
# select records from the table
cursor.execute("SELECT * FROM employee")
rows = cursor.fetchall()
for row in rows:
print(row)
# update
cursor.execute("update employee set name = 'Rakesh’ where id = 101")
# delete a record from the table
cursor.execute("delete from employee where id = 103")
# drop the table
cursor.execute("DROP TABLE employee")
# commit
conn.commit()
cursor.close()
conn.close()

VEDANT SCORE BOOSTER Page 37


PYTHON PROGRAMMING

3. Explain 10 widgets used in GUI Programming.


In Tkinter, widgets are the low-level components used to build the
graphical user interface (GUI). Here are some of the most commonly used
widgets in Tkinter:
1. Label: This widget is used to display text or images.
Ex:
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello World!")
label.pack()
root.mainloop()
2. Button: This widget is used to trigger an action when clicked.
Ex:
import tkinter as tk
def button_click():
print("Button clicked")
root = tk.Tk()
button = tk.Button(root, text="Click Me!", command=button_click)
button.pack()
root.mainloop()
3. Entry: This widget is used to get user input through a single line text box.
Ex:
import tkinter as tk
def submit():
value = entry.get()
print("User entered:", value)
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
submit_button = tk.Button(root, text="Submit", command=submit)
submit_button.pack()
root.mainloop()

VEDANT SCORE BOOSTER Page 38


PYTHON PROGRAMMING

4. Text: This widget is used to display or edit multi-line text.


Ex:
import tkinter as tk
root = tk.Tk()
text = tk.Text(root)
text.pack()
text.insert(tk.END, "This is a multi-line text widget.")
root.mainloop()

5. Checkbutton: This widget is used to toggle a boolean value.


Ex:
import tkinter as tk
root = tk.Tk()
varl = tk.BooleanVar()
var2 = tk.BooleanVar()
ckb1 = tk.Checkbutton(root, text="Pthon", variable=var1)
ckb2 = tk.Checkbutton(root, text="Java", variable=var2)
ckbl.pack()
ckb2.pack()
root.mainloop()

6. Radiobutton: This widget is used to select a single option from a group of


options.

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()

VEDANT SCORE BOOSTER Page 39


PYTHON PROGRAMMING

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( )

8. Scale: This widget is used to select a value from a range of values by


dragging a slider.

Ex:

import tkinter as tk
root = tk.Tk()
scale = tk.Scale(root, from_=0, to=100, orient=tk. HORIZONTAL)
scale.pack()
root.mainloop( )

9. Canvas: This widget is used to draw graphics, shapes, and images.


Ex:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200)
canvas.pack()
canvas.create_rectangle(50, 50, 150, 150, fill="red")
root.mainloop()

VEDANT SCORE BOOSTER Page 40


PYTHON PROGRAMMING

10. Menu: This widget is used to create menus and sub-menus.

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()

6. List any 4 operations on array using Numpy?

Four operations on arrays using NumPy


1. Creating arrays - You can create arrays of any size and shape using NumPy.
2. Indexing and slicing - You can access individual elements or slices of an array
using indexing and slicing.
3. Mathematical operations - NumPy provides a wide range of mathematical
functions that can be applied to arrays.
4. Aggregation functions - NumPy provides several aggregation functions such as
sum, mean, min, and max that can be used to summarize data in an array.

VEDANT SCORE BOOSTER Page 41


PYTHON PROGRAMMING

4. Write a python program to draw line chart.

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:

import matplotlib.pyplot as plt


# Sample data
x=[1,2,3,4,5]
y=103,2,4,1,5]
# Create line chart
plt.plot(x, y)
# Add labels and title
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title('Line chart example')
# Show the plot
plt.show()

Output:

VEDANT SCORE BOOSTER Page 42


PYTHON PROGRAMMING

5. Write a python program to draw Bar chart.


Bar 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 categories and values for the
bar chart.
Ex:
import matplotlib.pyplot as plt
#Sample data
x=[A''B E'
v=13,7,2,59]
# Create vertical bar chart
plt.bar(x, y)
# Add labels and title
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title('Vertical bar chart example')
# Show the plot
plt.show()

Output:

VEDANT SCORE BOOSTER Page 43


PYTHON PROGRAMMING

6. Write a python program to draw Bar chart

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:

VEDANT SCORE BOOSTER Page 44


PYTHON PROGRAMMING

7. Write a python program to draw Bar chart

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:

VEDANT SCORE BOOSTER Page 45


PYTHON PROGRAMMING

6. What are operations on Dataframe?

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.

VEDANT SCORE BOOSTER Page 46

You might also like