SLP Imp-Questions - Answer
SLP Imp-Questions - Answer
Image Processing Application: Python contains many libraries that are used to work with the
image. The image can be manipulated according to our requirements. Examples of image processing
libraries are: OpenCV, Pillow
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
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'>
Prepared by: Department of Computer Engineering Page 3
Subject:Scripting Language –Python Subject Code:4330701
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 = 'Ami Patel'
>>>a=”Ami Patel”
b) Lists: List is also a sequence of values of any type. List is enclosed in square brackets.
Example
Student = [“Neha”, 567, “CS”]
c) Tuples: Tuples are a sequence of values of any type, and are indexed by integers. Tuples are
enclosed in ().
Student = (“Neha”, 567, “CS”)
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'}
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.
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:
Arithmetic Operator
Relational Operator
Logical Operator
Bitwise Operator
Assignment Operator
Membership Operator
Arithmetic Operator
Bitwise Operator:
Assignment Operator
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:
Example: Python if Statement
num = 3
if num > 0:
print(“It is a positive number.")
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:
Prepared by: Department of Computer Engineering Page 7
Subject:Scripting Language –Python Subject Code:4330701
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
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
Output: Output:
Negative number b is max
while test_expression:
Body of while
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
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
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(‘ ‘)
Output: Output:
* 1
** 12
*** 123
**** 1234
***** 12345
11. Explain switch case statement with flowchart, syntax and example.
Python Switch case is a selection control statement.
The switch expression evaluated once.
The value of the expression is compared with the value of each case.
If there is a match, the associated block of code is executed.
Python does not have its inbuilt switch case statement.
We have to implement using different methods.
Using Function and Lamda Function
Using Dictionary Mapping
Using Python classes
Using if-elif-else
Day = {
1: monday,
2: tuesday,
3: wednesday,
4: thursday,
5: friday,
6: saturday,
7: sunday
}
def DayName(dayofWeek):
return Day.get(dayofWeek,default)( )
print(DayName (3))
print(DayName (8))
Output:
Wednesday
Incorrect day
12. 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.
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
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]
x.append(7)
print(x) Output: [1, 3, 5, 7]
x[2:2] = [5, 7]
del x[2]
print(x) Output:[19,20,40,50]
Output: 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])
print(x[-3])
Output:
40
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[:]) #Out put: (2, 4, 6, 8)
print(x[1:]) # Out put: (4, 6, 8)
print(x[:2]) #Out put: (2, 4)
print(x[1:3]) #Out put: (4, 6)
16. 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}
Prepared by: Department of Computer Engineering Page 16
Subject:Scripting Language –Python Subject Code:4330701
x.add(2) {1, 2, 3}
print(x)
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
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.
Prepared by: Department of Computer Engineering Page 17
Subject:Scripting Language –Python Subject Code:4330701
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))
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
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.
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.
Example :
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
22. What are modules in Python? Write Example of user defined module.
Modules is a file containing Python statements and definitions.
Modules are pre defined 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
Python contains built-in modules that are already programmed into the language and user
defined modules are 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.
result = a + b
print( result)
import example
Using the module name we can access the function using the dot ( . ) operator. For example:
>>> example.add(4,5.5)
9.5
23. List out method of rand module. Explain any four with example.
random() ,uniform(),randint( ) ,randrange( ),choice( ),choices( ),shuffle()
random( ): It is used to generate random floats between 0 to 1.
Syntax: random.random()
Example: import random
print(random.random())
Output: 0.371793355562307
uniform( ): It is used to generate random floats between two given parameters.
Syntax: random.uniform(First number,Second number)
Example: import random
print(random.uniform(1,10))
Output: 7.771509161751196
randint( ): It returns a random integer between the given integers.
Syntax: random.randint(First number,Second number)
Example: import random
print(random.randint(1,10))
Output: 3
shuffle(): It is used to shuffle a sequence (list). Shuffling means changing the position of the
elements of the sequence
Syntax: random.shuffle(sequence)
Output : 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))
Output :5
fabs(): It returns the absolute value of the number.
Example :import math
print (math.fabs(-10))
Output : 10.0
fmod(): It returns the reminder of x/y.
Example : import math
print (math.fmod(10,3))
Output : 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))
Output: 7.38905609893065
25. Explain main classes of Date and Time module with one Example.
date –Its attributes are year, month and day.
time –Its attributes are hour, minute, second, microsecond, and tzinfo.
datetime – Its a combination of date and time along with the attributes year, month, day, hour,
minute, second, microsecond, and tzinfo.
timedelta – A duration expressing the difference between two date, time, or datetime instances
to microsecond resolution.
tzinfo – It provides time zone information objects.
timezone – A class that implements the tzinfo abstract base class as a fixed offset from the
UTC
Example:1 Get current date and time(Using datetime class)
import datetime Output
d=datetime.datetime.now()
print(d) 2022-11-28 12:40:36.467347
27. 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.
import Game.Level.start
Now create one more python file with name p2.py in EMP directory with following code.
def getSalary():
salary=[1000,2000,3000]
return salary
pip -V
29. How to use slicing operator for string. Explain with example.
A segment of a string is called a slice.
Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
Syntax:[Start: stop: steps]
Slicing will start from index and will go up to stop in step of steps.
Default value of start is 0,
Stop is last index of list
And for step , default is 1
str = 'Hello World!' Output
print (str ) Hello World!
print(str[0] ) H
print (str[2:4]) ll
print (str[2:] ) llo World!
print (str * 2) Hello World!Hello World!
str="Hello World" Output
for s in str[0:11:1]: Hello World
print(s)
30. 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='+-'
Prepared by: Department of Computer Engineering Page 26
Subject:Scripting Language –Python Subject Code:4330701
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.
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
31. 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
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
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()