0% found this document useful (0 votes)
4 views26 pages

sl_imp-que_ans_wp

The document provides an overview of Python programming, covering its features, applications, basic program structure, keywords, identifiers, variables, data types, input/output methods, operators, selection statements, loops, and control statements. It includes examples and explanations of various concepts such as arithmetic operators, if statements, while loops, and the use of break, continue, and pass statements. This serves as a comprehensive guide for students learning scripting languages, specifically Python.

Uploaded by

saymamansuri561
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)
4 views26 pages

sl_imp-que_ans_wp

The document provides an overview of Python programming, covering its features, applications, basic program structure, keywords, identifiers, variables, data types, input/output methods, operators, selection statements, loops, and control statements. It includes examples and explanations of various concepts such as arithmetic operators, if statements, while loops, and the use of break, continue, and pass statements. This serves as a comprehensive guide for students learning scripting languages, specifically Python.

Uploaded by

saymamansuri561
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/ 26

VPMP Polytechnic, Gandhinagar

Department of Computer Engineering


IMP Questions with answer
Subject: Scripting Language (DI02000101)
Semester: 2nd
1. List and explain features of Python.
 Python is object-oriented: Structure supports such concepts as polymorphism, operation overloading
and multiple inheritance.
 Indentation: Indentation is one of the greatest feature in python.
 It is free (open source): Downloading python and installing python is free and easy.
 It is Powerful: It provides Dynamic typing, Built-in types and tools, Library utilities, and Automatic
memory management
 It is Portable: Python runs virtually every major platform used today
 It is easy to use and learn: It has no intermediate compile. Python Programs are compiled
automatically to an intermediate form called byte code, which the interpreter then reads.
 Interpreted Language: Python is processed at runtime by python Interpreter
 Interactive Programming Language: Users can interact with the python interpreter directly for
writing the programs
 Straight forward syntax: The formation of python syntax is simple and straight forward which also
makes it popular.

2. Write Application of python.


 Web Applications: It is used to develop web applications. Python provides many useful frameworks
like Django and Pyramid framework, Flask and Bottle (Micro-framework)
 Desktop GUI Applications: Graphical User Interface provides a smooth interaction to any
application. Ex: Tk GUI library.
 Console-based Application: It run from the command-line or shell. These applications are computer
program which are used commands to execute.
 Software Development: Python is useful for the software development process. It works for control
and management, testing, etc.
 Scientific and Numeric: Most suitable for AI(Artificial intelligence) or Machine Learning. It has
scientific and mathematical libraries, which makes easy to solve complex calculations.
 Business Applications: Python provides scalability and readability for business application like E-
commerce and ERP.
 Audio or Video-based Applications: It is used to create multimedia applications.
 Enterprise Applications: Python can be used to create applications for Enterprise or an Organization.
Some real-time applications are OpenERP, Tryton, Picalo, etc.
 Image Processing Application: The image processing is used to manipulate images. Python provides
libraries for that. Example: OpenCV, Pillow.

VPMP Polytechnic, Department Of Computer Engineering Page 1


3. Explain basic structure of Python Program.
Import statements
// import statements are used to include library files to the python program
Function definitions
//This section include the definitions of various functions written in a Python Program
Program statements
// This section include the set of statements for solving the given problem.

There are two modes for using the Python interpreter:


 Interactive Mode
 Script Mode
Running Python in interactive mode:
 Without passing python script file to the interpreter, directly execute code to Python prompt.
 Once you’re inside the python interpreter, then you can start.
 >>> print("hello world")
Output: hello world
Running Python in script mode:
 Alternatively, programmers can store Python script source code in a file with
the .py extension, and use the interpreter to execute the contents of the file.
 To execute the script by the interpreter, you have to tell the interpreter the name of the file.

4. Explain keyword, identifier and variable.


Identifiers
 Identifier is a name given to various programming elements such as a variable, function, class,module
or any other object.
 rules to create an identifier.
1. The allowed characters are a-z, A-Z, 0-9 and underscore (_)
2. It should begin with an alphabet or underscore
3. It should not be a keyword
4. It is case sensitive
5. No blank spaces are allowed.
6. It can be of any size
 Valid identifiers examples : si, rate_of_interest, student1, ageStudent
 Invalid identifier examples : rate of interest, 1student, @age
Keywords:Keywords are the identifiers which have a specific meaning in python, there are 33 keywords in
python. These may vary from version to version

Variables :When we create a program, we often need store values so that it can be used in a program. We
use variables to store data which can be manipulated by the computer program.
 Every variable has a name and memory location where it is stored.
 It Can be of any size
VPMP Polytechnic, Department Of Computer Engineering Page 2
 Variable name Has allowed characters, which are a-z, A-Z, 0-9 and underscore (_)
 Variable name should begin with an alphabet or underscore
 Variable name should not be a keyword
 Variable name should be meaningful and short
 Generally, they are written in lower case letters
 A type or datatype which specify the nature of variable (what type of values can be stored in
 We can check the type of the variable by using type command
>>> type(variable_name)

5. Explain datatype with example.


Number: Number data type stores Numerical Values. These are of three different types:
a) Integer & Long
b) Float/floating point
c) Complex
a) Integers are the whole numbers consisting of + or – sign like 100000, -99, 0, 17.
e.g. age=19
salary=20000

b) Floating Point: Numbers with fractions or decimal point are called floating point numbers.A floating
point number will consist of sign (+,-) and a decimal sign(.)
e.g. temperature= -21.9,growth_rate= 0.98333328

c) Complex: Complex number is made up of two floating point values, one each for real and imaginary part.
For accessing different parts of a variable x we will use x.real and x.imag. Imaginary part of the number is
represented by j instead of i, so 1+0j denotes zero imaginary part.
Example
>>> x = 1+0j
>>> print x.real,x.imag
1.0 0.0

Boolean: Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

Sequence: A sequence is an ordered collection of items, indexed by positive integers. Three types of
sequence data type available in Python are Strings, Lists & Tuples.
a)String: is an ordered sequence of letters/characters. They are enclosed in single quotes (‘’) or double (“”).
Example
>>> a = 'Preeti Gajjar'
>>>a=”Preeti Gajjar”
b) Lists: List is also a sequence of values of any type. List is enclosed in square brackets.
Example
Student = [“Jia”, 567, “CS”]
c) Tuples: Tuples are a sequence of values of any type, and are indexed by integers. Tuples are enclosed in ().
Student = (“Jeni”, 567, “CS”)

VPMP Polytechnic, Department Of Computer Engineering Page 3


Sets
Set is an unordered collection of values, of any type, with no duplicate entry. Sets are immutable.
Example
s = set ([1,2,3,4])

Dictionaries: Dictionaries store a key – value pairs, which are accessed using key. Dictionary is enclosed in
curly brackets.
Example
d = {1:'a', 2:'b', 3:'c'}

6. Explain input and print method of python.


Print method: A statement is print with the help of print() method.
syntax : print(“message to be printed”) Or print(‘message to be printed’) or print(variable_name)
Example: x=10
print(x)
Output: 10

Syntax: print(“message to be printed”, variable_name)


Example:
x=10
print("value of x",x)

Output: value of x 10

Syntax: print(‘message to be printed’, variable_name)


Example:
x=10
print(‘value of x’,x)
Output: value of x 10

Input method:A value can be input from the user with the help of input() method. input method return a
string. It can be changed to other datatypes by using type.

Syntax: variable_name = input(“Enter any number”)

Example:
name = input(“Enter your name”)
age= int(input(“Enter you age”))

7. List out operator and explain arithmetic, assignment and bitwise operator.
Types of operators:
1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Bitwise Operator
5. Assignment Operator
6. Membership Operator

VPMP Polytechnic, Department Of Computer Engineering Page 4


Arithmetic Operator

Bitwise Operator:

VPMP Polytechnic, Department Of Computer Engineering Page 5


Assignment Operator

8. Explain python selection statements with flowchart, syntax and example.

 if Statement : statement execute only if the result of condition is true .

Flowchart Syntax

if test expression:
statement(s)

 The program checks the test expression. If the test expression is True, then statement(s) will be executed.
 If the test expression is False, the statement(s) is not executed.
 In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation
and the first unindented line marks the end.

Example: Python if Statement


num = 3
if num > 0:
print(“It is a positive number.")
VPMP Polytechnic, Department Of Computer Engineering Page 6
Output:
It is a positive number.

 if else Statement :When we have to select only one option from the given two option, then we use if …else.
Flowchart Syntax

if test expression:
Body of if
else:
Body of else

 The if..else statement evaluates test expression and will execute the body of if only when the test condition is
True.
 If the condition is False, the body of else is executed. Indentation is used to separate the blocks.
Example: Python if…else Statement
a=7
b=0
if (a > b):
print("a is greater than b")
else:
print("b is greater than a")
Output:
a is greater than b

 Nested if-else : Nested “if-else” statements mean that an “if” statement or “if-else” statement is present
inside another if or if-else block.

Syntax
if ( test condition 1):
if ( test condition 2):
Statement1
else:
Statement2
else:
Statement 3
 First test condition1 is checked, if it is true then check condition2.
 If test condition 2 is True, then statement1 is executed.
 If test condition 2 is false, then statement2 is executed.
 If test condition 1 is false, then statement3 is executed

VPMP Polytechnic, Department Of Computer Engineering Page 7


Example: Python Nested if…else Statement
a=int(input("Enter A: "))
b=int(input("Enter B: "))
c=int(input("Enter C: "))
if a>b:
if a>c:
max=a
else:
max=c
else:
if b>c:
max=b
else:
max=c

print("Maximum = ",max)

Output:
Enter A: 23
Enter B: 2
Enter C: 56
Maximum = 56

 if-elif-else statements
Flowchart Syntax

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

 The elif is short for else if.


 It allows us to check for multiple expressions.
 If the condition for if is False, it checks the condition of the next elif block and so on.
 If all the conditions are False, the body of else is executed.
 Only one block among the several if...elif...else blocks is executed according to the condition.

Example: Python if-elif-else Statement


num = -3 a,b,c=12,45,3
if num > 0: if a>b and a>c:
print("Positive number") print("a is max")

VPMP Polytechnic, Department Of Computer Engineering Page 8


elif num == 0: elif b>a and b>c:
print("Zero") print("b is max")
else: else:
print("Negative number") print("c is max")

Output: Output:
Negative number b is max

9. Explain while loop with flowchart, syntax and example.


Flowchart Syntax

while test_expression:
Body of while

 Loops are either infinite or conditional.


 In the while loop, test expression is checked first.
 The body of the loop is entered only if the test_expression evaluates to True.
 After one iteration, the test expression is checked again. This process continues until the test_expression
evaluates to False.
 The statements that are executed inside while can be a single line of code or a block of multiple statements
Example:
x=1
while(x<=5):
print(x)
x+=1
Output:
1
2
3
4
5

10. Explain for loop and nested for loop with flowchart, syntax and example.
For loop:
 Python for loop is used for repeated execution of a group of statements for the desired number of times.
 It iterates over the items of lists, tuples, strings, the dictionaries and other iterable objects

VPMP Polytechnic, Department Of Computer Engineering Page 9


Flowchart:

Example:
for i in range(1,6): a=[10,12,13,14]
print(i) for i in a:
print(i)
Output: Output:
1 10
2 12
3 13
4 14
5

Nested for loop:Nested loops mean loops inside a loop.


For example, while loop inside the for loop, for loop inside the for loop, etc.
Syntax: Syntax:

for var in sequence: while expression:


for var in sequence: while expression:
statements(s) statement(s)
statements(s) statement(s)

Example :1 Example :2

rows = 5 rows = 5
for i in range(1, rows + 1): for i in range(1, rows + 1):
for j in range(1, i + 1): for j in range(1, i + 1):
print('*',end=' ') print(j,end=' ')
print(‘ ‘) print(‘ ‘)

VPMP Polytechnic, Department Of Computer Engineering Page 10


Output: Output:

* 1
** 12
*** 123
**** 1234
***** 12345

11. Explain break, continue and pass statement with flowchart, syntax and example.
 break statement
 The break statement terminates the loop containing it.
 Control of the program flows to the statement immediately after the body of the loop.
 The break statement can be used in both while and for loops.

Syntax:

break

Example:
for i in range(1,11):
print(i)
if i == 2:
break

Output:
1
2
 continue statement
 The continue statement in Python returns the control to the beginning of the while loop.
 The continue statement can be used in both while and for loops.

VPMP Polytechnic, Department Of Computer Engineering Page 11


Syntax:

continue

Example:
n=int(input("enter n"))
for i in range(1,n):
if(i==5):
continue
print(i)

Output:
enter n10
12346789

 Pass Statement
 the pass statement is a null statement.
 Nothing happens when the pass is executed.
 It results in no operation (NOP).
 When the user does not know what code to write, so user simply places pass at that line. Sometimes, pass is
used when the user doesn’t want any code to execute.
 Syntax:
pass
 Example
a= {'h', 'e', 'l', 'l','o'}
for val in a:
pass

12. Define List. Write Characteristics of list.


List: It is used to store the sequence of various types of data.
Characteristics of List:
 List is ordered.
 It allows duplicate members.
 It is a general purpose, most widely used in data structures.
 It is mutable type(We can modify its element after it is created)
 Elements of list can access by index.
 To use a list, you must declare it first. It is declare using square brackets and separate values with commas.

VPMP Polytechnic, Department Of Computer Engineering Page 12


13. How to create a list. Explain append(),extend(),insert() and delete operations on list.
create a list :In Python, a list is created by placing elements inside square brackets [], separated by commas.
Example:
x = [1, 2, 3]
print(x)
Output:
[1, 2, 3]

Append( ) and extend( ):


 We can add one item to a list using the append() method or add several items using the extend() method.
x = [1, 3, 5]

x.append(7)
print(x) Output: [1, 3, 5, 7]

x.extend([9, 11, 13])


print(x) Output: [1, 3, 5, 7, 9, 11, 13]

Insert( )
 We can insert one item at a desired location by using the method insert() or insert multiple items by squeezing
it into an empty slice of a list.
x = [1, 9]
x.insert(1,3)

print(x) Output: [1, 3, 9]

x[2:2] = [5, 7]

print(x) Output: [1, 3, 5, 7, 9]

Delete
 We can delete one or more items from a list using the Python del statement. It can even delete the list entirely.
x = [10,20,30,40,50]

del x[2]
print(x) Output:[19,20,40,50]

del x # delete the entire list

print(x) # Error: List not defined

14. Write Characteristics of Tuple. Explain indexing and slicing in tuple.


Tuple: In Python, a tuple is created by placing elements inside round brackets [], separated by commas. A
tuple in Python is similar to a list.

VPMP Polytechnic, Department Of Computer Engineering Page 13


Characteristics of Tuple:
 It is ordered.
 It allows duplicate members.
 It is immutable type(We cannot modify its element after it is created)
 Elements of Tuple can access by index.
 To use a tuple, you must declare it first. It is declare using ( ) brackets and separate values with commas.

Access tuple items(Indexing):

 We can use the index operator [] to access an item in a tuple, where the index starts from 0.
 So, a tuple having 6 elements will have indices from 0 to 5.
Example:
>>> x=(10,20,30)
>>> print(x[2]) #30

Negative Indexing: Python allows negative indexing for its sequences. The index of -1 refers to the last item,
-2 to the second last item and so on.

x = (10,20,30,40)
print(x[-1]) #40
print(x[-3]) #20

Slicing
We can access a range of items in a tuple by using the slicing operator colon :
x=(2,4,6,8)
print(x[:]) #Output: (2, 4, 6, 8)
print(x[1:]) # Output: (4, 6, 8)
print(x[:2]) #Output: (2, 4)
print(x[1:3]) #Output: (4, 6)

15. Write Characteristics of Set. Explain add(),update(),remove() and discard() method of set.
A set is an unordered collection of items.
Characteristics of Set:
 Sets are unordered.
 Set element is unique. Duplicate elements are not allowed.
 Set are immutable.(Can not change value)
 There is no index in set. So they donot support indexing or slicing operator.
 The set are used for mathematical operation like union,intersection,difference etc.

Modifying a set in Python (add( ) and update())

 We can add a single element using the add() method, and multiple elements using the update() method.
x = {1, 3} Output:
print(x) {1, 3}

x.add(2) {1, 2, 3}

VPMP Polytechnic, Department Of Computer Engineering Page 14


print(x)

x.update([2, 3, 4]) {1, 2, 3, 4}


print(x)

Removing elements from a set (remove() and discard())


 A particular item can be removed from a set using the methods discard() and remove().

 The only difference between the two is that the discard() function leaves a set unchanged if the element is
not present in the set. On the other hand, the remove() function will raise an error in such a condition (if
element is not present in the set).
x = {1, 3, 4, 5, 6} Output:
print(x) {1, 3, 4, 5, 6}
x.discard(4) {1, 3, 5, 6}
print(x)
{1, 3, 5}
x.remove(6)
print(x)

x.discard(2) {1, 3, 5}
print(x)
Traceback (most recent call last):
x.remove(2) File "<string>", line 28, in <module>
KeyError: 2

16. Explain mathematical operations on Set(Union,Intersection,difference and symmetric difference)


OR Explain Python Set operations.
Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric
difference.

Set Union: Union of A and B is a set of all elements from both sets. Union is performed using | operator.
Same can be accomplished using the union() method.
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A | B) print(A.union(B))
print(B.union(A))

Output: Output:
{1, 2, 3, 4, 5, 6, 7, 8} {1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection: Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the intersection() method.

VPMP Polytechnic, Department Of Computer Engineering Page 15


A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A & B) print(A.intersection(B))
print(B.intersection(A))

Output:
Output: {4, 5} {4, 5}
{4, 5}

Set Difference: Difference of the set B from set A(A - B) is a set of elements that are only in A but not in
B. Similarly, B - A is a set of elements in B but not in A. Difference is performed using - operator. Same can
be accomplished using the difference() method.
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A - B) print(A.difference(B))
print(B. difference (A))

Output: {1,2,3} Output:


{1,2,3}
{6,7,8}

Set Symmetric Difference: Symmetric Difference of A and B is a set of elements in A and B but not in both
(excluding the intersection).Symmetric difference is performed using ^ operator. Same can be accomplished
using the method symmetric_difference().
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A ^ B) print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
Output:{1,2,3,6,7,8}
Output: {1,2,3,6,7,8}
{1,2,3,6,7,8}

17. Write Characteristics of Dictionary. Explain operations on dictionary


 Python dictionary is an ordered collection of items.
 Each item of a dictionary has a key/value pair.
Characteristics of Dictionary:
 It is used to store data in a key-value pair format.
 It is mutable(changeable).
 Duplicate values are not allowed.
 Key must be a single element.
 Value can be of any type such as list, tuple, integer etc.
Changing and Adding Dictionary elements:
 We can add new items or change the value of existing items using an assignment operator.
 If the key is already present, then the existing value gets updated.
 In case the key is not present, a new (key: value) pair is added to the dictionary.

x = {'name': 'abc', 'rollno': 1} Output


print(x) {'name': 'abc', 'rollno': 1}

VPMP Polytechnic, Department Of Computer Engineering Page 16


x['rollno'] = 20 # update value {'name': 'abc', 'rollno': 20}
print(x)

x['address'] = 'xyz' # adding value {'name': 'abc', 'rollno': 20, 'address': 'xyz'}
print(x)

Removing elements from Dictionary:


 We can remove a particular item in a dictionary by using the pop() method.
 The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the
dictionary.
 All the items can be removed at once, using the clear() method.
 We can also use the del keyword to remove individual items or the entire dictionary itself.
Using pop( ) Output:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 16
print(squares.pop(4)) # remove a particular item, returns its value {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
Using popitem( ) Output:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.popitem()) # remove an arbitrary item, return (key,value) (5, 25)
print(squares) {1: 1, 2: 4, 3: 9, 4: 16}
Using clear( ) Output:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
squares.clear()
print(squares) {}
Using del keyword Output:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
del squares[2]
print(squares) {1: 1, 3: 9, 4: 16, 5: 25}

del squares
print(squares) NameError: name
'squares' is not defined

18. Define function. Why do we need it?


 A function is a block of code which only runs when it is called.
 In Python, a function is a group of related statements that performs a specific task.
 Functions help break our program into smaller and modular chunks.
 As our program grows larger and larger, functions make it more organized and manageable.
 It avoids repetition and makes the code reusable.
 You can pass data, known as parameters; into a function.
 A function can return data as a result.

VPMP Polytechnic, Department Of Computer Engineering Page 17


19. Give difference between User Define Function and Built in Function.

20. What is Recursion? Explain with example.


 A Function calls itself is said to be a recursion.
 Recursion is the process of defining something in terms of itself.
Python Recursive Function:
 Function can call other functions. It is even possible for the function to call itself. These types of construct
are termed as recursive functions.
 The following image shows the workings of a recursive function called recurse.

Example: Find the factorial of an integer.


 Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of
6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example1 :
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
calling a function:
num = 3
print("The factorial of", num, "is", factorial(num))

Output:
The factorial of 3 is 6

Example2 :
Write a program to print Fibonacci sequence up to n numbers using recursion. Fibonacci sequence is defined as
below: 𝐹𝑖𝑏𝑜𝑛𝑎𝑐𝑐𝑖 𝑆𝑒𝑞𝑢𝑒𝑛𝑐𝑒= 1 1 2 3 5 8 13 21… 𝑤ℎ𝑒𝑟𝑒 𝑛𝑡ℎ𝑡𝑒𝑟𝑚 𝑥𝑛= 𝑥𝑛−1+ 𝑥𝑛−2

Code:
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))

VPMP Polytechnic, Department Of Computer Engineering Page 18


Output:
Enter number of terms:5
Fibonacci sequence:
0
1
1
2
3

21. What are modules in Python? Write Example of user defined module.
 Modules is a file containing Python statements and definitions.
 Modules are predefined files that contain the python codes which include the basic functionality of
class, methods ,variables etc.
 Modules can be divided in to two parts: User defined and built in
o Built-in modules: That are already programmed into the language
o User defined modules: created by user.
 We can define our most used functions in a module and import it, instead of copying their definitions
into different programs.
 A file containing Python code, for example: example.py, is called a module, and its module name
would be example.

 Example of user defined module (module name: example):


def add(a, b):
result = a + b
print( result)
How to import modules in Python?
We use the import keyword to do this: import example
Using the module name we can access the function using the dot ( . ) operator. For example:

>>> example.add(4,5.5)
9.5

22. Explain any five mathematical functions of math module.


ceil(): Rounds a number up to the nearest integer
Example : import math
print(math.ceil(8.23))
Output : 9
floor():Rounds a number down to the nearest integer
Example : import math
print(math.floor(8.23))
Output : 8

sqrt():It returns the square root of the number.


Example: import math
print(math.sqrt(25)) #5
pow():It receives two arguments, raises the first to the second and give result.
Example: import math
VPMP Polytechnic, Department Of Computer Engineering Page 19
print(math.pow(2,4)) # 16.0
factorial(): It returns the factorial of a given number.
Example: import math
print(math.factorial(4)) #24
gcd(): It is used to find the greatest common divisor of two numbers passed as the arguments.
Example :import math
print(math.gcd(10,35)) #5
fabs(): It returns the absolute value of the number.
Example :import math
print (math.fabs(-10)) #10.0
fmod(): It returns the reminder of x/y.
Example : import math
print (math.fmod(10,3)) #1.0
exp(): It returns a float number after raising e to the power of a given number. (e**x)
Example : import math
print (math.exp(2)) #7.38905609893065

23. List out types of plots in Matplotlib. Explain any one with example.
Matplotlib is a library for creating static, animated and interactive visualization in Python.
Types of Plots: Line Plot, Scatter Plot, Area Plot, Bar Graph, Histogram, Pie plot etc.
1. Line plot :
EXAMPLE: OUTPUT:
from matplotlib import pyplot as plt
x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2]
plt.plot(x,y)
plt.show()

24. What is package? How to Create and import package. Explain with example.
 As a directory can contain subdirectories and files, a Python package can have sub-packages and
modules.
 Python has packages for directories and modules for files.
 A directory must contain a file named __init__.py in order for Python to consider it as a package. This file
can be left empty
 Suppose we are developing a game. One possible organization of packages and modules could be as
shown in the figure below.

VPMP Polytechnic, Department Of Computer Engineering Page 20


Importing module from a package
 We can import modules from packages using the dot (.) operator.
 For example, if we want to import the start module in the above example, it can be done as follows:

import Game.Level.start

 Creating User Defined Package:


 Create a directory with the name EMP in home directory.
 Create a Python source file with name p1.py in EMP directory with following code.
def getName():
name=['a','b','c']
return name

 Now create one more python file with name p2.py in EMP directory with following code.
def getSalary():
salary=[1000,2000,3000]
return salary

 Now create __init__.py without any code in EMP directory.


 __init__.py converts Emp directory to Emp package with two modules p1 and p2.
 Importing a package in Python
 To use the module defined in Emp package, Create one file Test.py in home directory with code:
from Emp import p1
from Emp import p2
print(p1.getName())
print(p2.getSalary())
Now run Test.py to see the Output:
Output:['a', 'b', 'c']
[1000, 2000, 3000]

VPMP Polytechnic, Department Of Computer Engineering Page 21


25. Write down steps for PIP Installation.
 PIP is the package manager for Python packages.
 It is a package management system used to install and manage software packages written in Python.
 We use pip to install packages that do not come with Python.
 Python pip comes preinstalled on 3.4 or older version of Python.
 To check whether pip is installed or not, type below command in terminal. It shows the version of pip
which is already installed in the system.
pip -version
 Pip use PyPI as the default source for packages. So type following command on command prompt for
installation of packages.
pip install packagename
 Pip will look for that package on PyPI and if found ,download it and install the package on local
system.
 For uninstalling a package type following command on command prompt.

pip uninstall packagename

Download and Install PIP:


 Download the get-pip.py file and store it in the same directory as python is installed.
 Change the current path of the directory in the command line to the path of the directory where get-
pip.py file exists.
 Type following command in command prompt and wait through the installation process.
python get-pip.py
 Type following command to check whether pip is installed successfully or not. If successfully installed
then display current version of it.

pip -V

26. Explain following function with example: isalnum( ), isalpha ( ), isdigit( ), isidentifier (), islower(),
isupper( ), and isspace( )
isalnum(): returns True if all the characters in the string is alphanumeric (number or alphabets or both).
Otherwise return False
s="abc" Output:
print(s.isalnum()) True
s='123' True
print(s.isalnum()) False
s='+-'
print(s.isalnum())

isalpha: returns True if all the characters in the string are alphabets. Otherwise return False
s="abc" Output:
print(s.isalpha()) True
s='123' False
print(s.isalpha())
Isdigit: returns True if all the characters in the string are digits. Otherwise return False.
VPMP Polytechnic, Department Of Computer Engineering Page 22
s="abc" Output:
print(s.isdigit()) False
s='123' True
print(s. isdigit ())
Isidentifier: returns True if string is an identifier or a keyword Otherwise return False.
print("hello".isidentifier()) Output:
print("for".isidentifier()) True
True
islower: returns True if all the characters in the string are in lowercase. Otherwise return False.
s = 'Python' Output:
print(s.islower()) False
isupper: returns True if all the characters in the string are in uppercase. Otherwise return False.
s = 'Python' Output:
print(s.isupper()) False

isspace : returns True if all the characters in the string are whitespace characters. Otherwise return False.
print("\n\t".isspace()) Output:
True

27. Explain following function with example: endswith(), startswith(), find(), rfind(), count()
endswith: Syntax: endswith(suffix, start, end)
 Returns True when a string ends with the characters specified by suffix.
 You can limit the check by specifying a starting index using start or an ending index using end.
s="Hello" Output:
print(s.endswith('lo')) True
print(s.endswith('lo',2,5)) True

startswith: Syntax:startswith(prefix, start, end):


 Returns True when a string begins with the characters specified by prefix.
 You can limit the check by specifying a starting index using start or an ending index using end.
s="Hello" Output:
print(s.startswith('He')) True
print(s.startswith('He',0,3)) True

Find: Syntax: find(str, start, end):


 Check whether str occurs in a string and outputs the index of the location.
 You can limit the search by specifying starting index using start or a ending index using end.
s = 'Hello World' Output:
ans = s.find('Hello') Substring found at index: 0
print("Substring found at index:", ans)

rfind: Syntax: rfind(str, start, end):


 Provides the same functionality as find(), but searches backward from the end of the string instead of the
starting.
 You can limit the search by specifying starting index using start or a ending index using end.
s = 'Hello World' Output:
ans = s.rfind('Hello')

VPMP Polytechnic, Department Of Computer Engineering Page 23


print("Substring found at index:", ans) Substring found at index: 0

count: Syntax: count(str, start, end):


 Counts how many times str occurs in a string.
 You can limit the search by specifying a starting index using start or an ending index using end.
s= "Hello Students Hello" Output:
print(s.count("Hello", 0, 5)) 1

28. List out Formatting function and explain any two.


Formatting functions: ljust(), rjust(),center(),format()
ljust: This method left aligns the string according to the width specified and fills the remaining space of the
line with blank space if ‘fillchr‘ argument is not passed.

Syntax: ljust(len, fillchr)


len: The width of string to expand it.
fillchr (optional): The character to fill in the remaining space.
s = "hello" Output:
print(s.ljust(10)) hello
print(s.ljust(10, '-')) hello-----
rjust: This method left aligns the string according to the width specified and fills the remaining space of the
line with blank space if ‘fillchr‘ argument is not passed.
Syntax: rjust(len, fillchr)
len: The width of string to expand it.
fillchr (optional): The character to fill in the remaining space.

s = "hello" Output:
print(s.rjust(10)) hello
print(s.rjust(10, '-')) -----hello
center: It creates and returns a new string that is padded with the specified character.
Syntax: string.center(length[, fillchar])
s="Hello World" Output:
print(s.center(20)) Hello World

29. Explain open() and close() for file with example.


open File:
 Before performing any operation on the file like reading or writing, first, we have to open that file.
 Open() is used to open a file.
 At the time of opening, we have to specify the mode, which represents the purpose of the opening file.
Syntax: file object = open(filename, access mode)
Example: f = open("a.txt", "r")

Where the following mode is supported:


r open an existing file for a read operation.
w open an existing file for a write operation. If the file already contains some data then it will be
overridden but if the file is not present then it creates the file as well.

VPMP Polytechnic, Department Of Computer Engineering Page 24


a open an existing file for append operation. It will not override existing data.
r+ To read and write data into the file. The previous data in the file will be overridden
w+ To write and read data. It will override existing data.
a+ To append and read data from the file. It will not override existing data.

close File:
 close() function closes the file and frees the memory space acquired by that file.
 It is used at the time when the file is no longer needed or if it is to be opened in a different file mode.
Syntax: File object.close()
Example: f = open("a.txt", "r")
f.close()

30. Explain read(),readline() and readlines () for file with example.


read( ) : Returns the read bytes in form of a string. It reads n bytes, if no n specified, reads the entire file.
Syntax: File object.read([n])
f=open("a.txt","r") Output:
print(f.read( )) hello everyone
f.close() Good morning
readline( ) : Reads a line of the file and returns in form of a string. For specified n, reads at most n bytes. It
does not reads more than one line.
Syntax: File object.readline([n])
f=open("a.txt","r") Output:
print(f.readline()) hello everyone
f.close()

Readlines( ): Reads all the lines and return them as each line a string element in a list.
Syntax: File_object.readlines()
f=open("a.txt","r") Output:
print(f.readlines( )) ['hello everyone\n', 'Good morning\n', 'Have a nice day\n']
f.close()

31. Explain write(), append mode with write() and writelines () for file with example.
write():The write() method writes a string to a text file.
Syntax: File_object.write(str1)
Inserts the string str1 in a single line in the text file.

f=open("E:/a.txt","w") Output:
f.write("Hello World") Open a.txt file ….. Hello World is display in text
f.close() file.

append mode: To append to a text file, you need to open the text file for appending mode.
When the file is opened in append mode, the handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.
f=open("E:/a.txt","a") Output:
f.write("Good Morning") Open a.txt file ….. Hello World Good Morning
f.close() is display in text file.

VPMP Polytechnic, Department Of Computer Engineering Page 25


writelines():The writelines() method write a list of strings to a file at once.
Syntax: file_object.writelines(L) for L = [str1, str2, str3]
For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a
single time.

f=open("E:/a.txt","w") Output:
lines=["Hello\n","good\n","morning"] Open a.txt file …..Below content is displayed in
f.writelines(lines) text file.
f.close()
Hello
good
morning

Note: Prepare manual Programs for GTU Exam…

VPMP Polytechnic, Department Of Computer Engineering Page 26

You might also like