sl_imp-que_ans_wp
sl_imp-que_ans_wp
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)
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”)
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:
1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Bitwise Operator
5. Assignment Operator
6. Membership Operator
Bitwise 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.
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
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
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
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(‘ ‘)
* 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.
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
x.append(7)
print(x) Output: [1, 3, 5, 7]
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)
x[2:2] = [5, 7]
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]
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.
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}
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.
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))
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}
x['address'] = 'xyz' # adding value {'name': 'abc', 'rollno': 20, 'address': 'xyz'}
print(x)
del squares
print(squares) NameError: name
'squares' is not defined
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))
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.add(4,5.5)
9.5
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.
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
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
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
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()
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.
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