0% found this document useful (0 votes)
462 views114 pages

Python Sem.2

Uploaded by

shivendrap677
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)
462 views114 pages

Python Sem.2

Uploaded by

shivendrap677
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/ 114

Seat No.: ________ Enrolment No.

______________

GUJARAT TECHNOLOGICAL UNIVERSITY


Diploma Engineering – SEMESTER – 3 (NEW) – EXAMINATION – Summer-2023

Subject Code: 4330701 Date: 18-07-2023


Subject Name: Scripting Language -Python
Time: 02:30 PM TO 05:00 PM Total Marks: 70
Instructions:
1. Attempt all questions.
2. Make suitable assumptions wherever necessary.
3. Figures to the right indicate full marks.
4. Use of programmable & communication aids are strictly prohibited.
5. Use of non-programmable scientific calculator is permitted.
6. English version is authentic.

Q.1 (a) List out features and application of python. 03


(અ) પાયથોનની વિશેષતાઓ અને એવલિકે શનની યાદી બનાિો. ૦૩
(b) Explain Input and Output statements in Python by giving examples. 04
(બ) પાયથોનમાાં ઇનપુટ અને આઉટપુટ સ્ટે ટમેન્ટ ઉદાહરણો આપીને સમજાિો. ૦૪
(c) List out arithmetic operations. Build python code that performs three arithmetic operations. 07
(ક) એવરથમેટીક ઓપરેશન્સની યાદી બનાિો, અને કોઈ પણ ત્રણ એવરથમેટીક ઓપરેશન્સ કરિા ૦૭
માટે નો પાયથોન કોડ બનાિો.
OR
(c) List out the rules for defining variables and Explain the assignment operators of python in 07
details.
(ક) ચિોને વ્યાખ્યાવયત કરિા માટે ના વનયમોની યાદી બનાિો અને પાયથોનના અસાઇનમેન્ટ ૦૭
ઓપરેટરોને વિગતોમાાં સમજાિો.
Q.2 (a) Explain if and if-else statement with a suitable example. 03
(અ) if અને if-else સ્ટે ટમેન્ટ યોગ્ય ઉદાહરણ સાથે સમજાિો. ૦૩
(b) Explain while loop with a suitable example. 04
(બ) while િૂપ યોગ્ય ઉદાહરણ સાથે સમજાિો. ૦૪
(c) Create a Python program to display the following patterns using loop concept. 07

*
**
***
****
*****

(ક) િૂપ કોન્સેલટનો ઉપયોગ કરીને નીચેની પેટનન દશાનિિા માટે એક પાયથોન પ્રોગ્રામ બનાિો. ૦૭

*
**
***
****
*****
OR
Q.2 (a) Explain if-elif-else statement with suitable example. 03
(અ) if-elif-else સ્ટે ટમેન્ટ યોગ્ય ઉદાહરણ સાથે સમજાિો. ૦૩
(b) Explain break, continue and pass statement with suitable example. 04
(બ) break, continue અને pass સ્ટે ટમેન્ટસ યોગ્ય ઉદાહરણ સાથે સમજાિો. ૦૪

1
(c) Create a Python program to display the following patterns using loop concept. 07
1
12
123
1234
12345
(ક) િૂપ કોન્સેલટનો ઉપયોગ કરીને નીચેની પેટનન દશાનિિા માટે એક પાયથોન પ્રોગ્રામ બનાિો. ૦૭
1
12
123
1234
12345
Q.3 (a) Explain how to create a Set in Python by giving example. 03
(અ) ઉદાહરણ આપીને પાયથોનમાાં Set કે િી રીતે બનાિિો તે સમજાિો. ૦૩
(b) Explain how to create Dictionary in Python. Write a Python program to concatenate two 04
dictionaries into a new one.
(બ) પાયથોનમાાં વડક્શનરી કે િી રીતે બનાિિી તે સમજાિો, બે વડક્શનરીને જોડી એક નિી વડક્શનરી ૦૪
બનાિિા માટે પાયથોન પ્રોગ્રામ િખો.
(c) Write a Python program to perform the below operations on the list: 07
▪ Read n numbers from a user
▪ Find positive numbers.
▪ Find negative numbers.
(ક) િીસ્ટમાાં નીચેની કામગીરી કરિા માટે પાયથોન પ્રોગ્રામ િખો: ૦૭
▪ યુસર પાસેથી n નાંબરો િાાંચો
▪ હકારાત્મક સાંખ્ યાઓ શોધો
▪ નકારાત્મક સાંખ્ યાઓ શોધો
OR
Q.3 (a) Explain how to create tuple in Python by giving example. 03
(અ) ઉદાહરણ આપીને પાયથોનમાાં tuple કે િી રીતે બનાિિો તે સમજાિો. ૦૩
(b) Explains how to create a dictionaries in Python. Write a Python program to check if a key 04
exists in a dictionary.
(બ) પાયથોનમાાં વડક્શનરી કે િી રીતે બનાિિી તે સમજાિો વડક્શનરી .માાં key અવસ્તત્િમાાં છે કે કે મ તે ૦૪
ચકાસિા માટે પાયથોન પ્રોગ્રામ િખો .
(c) Write a program to perform the below operations on the list: 07
▪ Read n numbers from a user
▪ Number of odd numbers.
▪ Number of even numbers.
(ક) િીસ્ટમાાં નીચેની કામગીરી કરિા માટે પાયથોન પ્રોગ્રામ િખો: ૦૭
▪ યુસર પાસેથી n નાંબરો િાાંચો
▪ એકી સાંખ્ યાઓ શોધો
▪ બેકી સાંખ્ યાઓ શોધો
Q.4 (a) List any six built-in functions of Python. 03
(અ) પાયથોનના કોઈપણ છ વબલ્ટ ઇન-ફન્ક્સાંનની યાદી બનાિો. ૦૩
(b) Explain a random module of Python with a suitable example. 04
(બ) પાયથોનના રેન્ડમ મોડ્યુિને યોગ્ય ઉદાહરણ સાથે સમજાિો. ૦૪
(c) Create a user-defined module with a simple functions for finding the area of a square, circle 07
and rectangle. Write a program to import the module and access functions defined in the
module.
(ક) ચોરસ, િતુનળ અને િાંબચોરસનુાં ક્ષેત્રફળ શોધિા માટે ના ફન્ક્સાંનનુાં વ્યાખ્યાવયત કરી એક મોડ્યુિ ૦૭
બનાિો. એક પ્રોગ્રામ િખો એમાાં એ મોડ્યુિ ઈમ્પોટન કરી વ્યાખ્યાવયત કરેિ ફન્ક્સાંનને ઍક્સેસ
કરો.
OR
Q.4 (a) Explain the user-defined function of Python with a suitable example. 03
(અ) પાયથોનના યુસર-વડફાઈન ફન્ક્સાંનને યોગ્ય ઉદાહરણ સાથે સમજાિો. ૦૩
(b) Explain math module of Python with suitable example. 04
(બ) પાયથોનના મેથ મોડ્યુિને યોગ્ય ઉદાહરણ સાથે સમજાિો. ૦૪
(c) Create a user-defined module with simple functions for addition, subtraction, multiplication 07
and division. Write a program to import the module and access functions defined in the
module.

2
(ક) સરિાળા, બાદબાકી, ગુણાકાર અને ભાગાકાર શોધિા માટે ના ફન્ક્સાંનને વ્યાખ્યાવયત કરી એક ૦૭
મોડ્યુિ બનાિોએક પ્રોગ્રામ િખો . એમાાં એ મોડ્યુિ ઈમ્પોટન કરી વ્યાખ્યાવયત કરેિ ફન્ક્સાંનને
ઍક્સેસ કરો.
Q.5 (a) Explain file handling basic Python function to open and close the text file. 03
(અ) ટે ક્સ્ટ ફાઇિને ખોિિા અને બાંધ કરિા માટે ફાઈિ હેન્ડવિાંગ બેવિક પાયથોન ફાં ક્શનને સમજાિો. ૦૩
(b) Explain to access string elements using index operator with a suitable example. 04
(બ) ઇન્ડેક્સ ઓપરેટરનો ઉપયોગ કરીને વસ્ટર ાં ગ એવિમેન્ટને એક્સેસ કરિા માટે યોગ્ય ઉદાહરણ સાથે ૦૪
સમજાિો.
(c) Write a Python program that reads a text file and counts the occurrences of each alphabet in 07
the file. The program should prompt the user to enter the filename.
(ક) એક પાયથોન પ્રોગ્રામ િખો જે ટે ક્સ્ટ ફાઇિ િાાંચે છે અને ફાઇિમાાં દરેક મૂળાક્ષરોની ગણતરી કરે છે . ૦૭
પ્રોગ્રામે િપરાશકતાનને ફાઇિ નામ દાખિ કરિા માટે પૂછિુાં જોઈએ.
OR
Q.5 (a) Explain the usage of given file handling methods in Python. 03
▪ read ( )
▪ readline ( )
▪ readlines ( )
(અ) પાયથોનમાાં આપેિ ફાઇિ હેન્ડવિાંગ પદ્ધવતઓનો ઉપયોગ સમજાિો. ૦૩
▪ read ( )
▪ readline ( )
▪ readlines ( )

(b) Explain usage of given string methods in Python. 04


▪ islower ( )
▪ isupper ( )
▪ isdigit ( )
▪ isalnum ()
(બ) પાયથોનમાાં આપેિ વસ્ટર ાં ગ પદ્ધવતઓનો ઉપયોગ સમજાિો. ૦૪
▪ islower ( )
▪ isupper ( )
▪ isdigit ( )
▪ isalnum ()
(c) Write a Python program to check whether a given string is palindrome or not. 07
(ક) આપેિ વસ્ટર ાં ગ પેવિન્ડર ોમ છે કે નહીાં તે તપાસિા માટે પાયથોન પ્રોગ્રામ િખો. ૦૭

3
Subject:Scripting Language –Python Subject Code:4330701

VPMP Polytechnic, Gandhinagar


Department of Computer Engineering
IMP Questions with answer
Subject: Scripting Language-Python (4330701)
Semester: 3rd
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: We can use Python to develop web applications. Python provides many useful
frameworks, and these are given below:
Django and Pyramid framework (Use for heavy applications)
Flask and Bottle (Micro-framework)
 Desktop GUI Applications: The GUI stands for the Graphical User Interface, which provides a
smooth interaction to any application. Python provides a Tk GUI library to develop a user interface.
 Console-based Application: Console-based applications 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 as a
support language and can be used to build control and management, testing, etc.
 Scientific and Numeric: Python language is the most suitable language for Artificial intelligence
or machine learning. It consists of many scientific and mathematical libraries, which makes easy to
solve complex calculations.
 Business Applications: E-commerce and ERP are an example of a business application. This kind
of application requires extensively, scalability and readability, and Python provides all these features.
 Audio or Video-based Applications : Python is flexible to perform multiple tasks and can be
used to create multimedia applications.
 Enterprise Applications: Python can be used to create applications that can be used within an
Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.

Prepared by: Department of Computer Engineering Page 1


Subject:Scripting Language –Python Subject Code:4330701

 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

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

Prepared by: Department of Computer Engineering Page 2


Subject:Scripting Language –Python Subject Code:4330701

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'}

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

Prepared by: Department of Computer Engineering Page 4


Subject:Scripting Language –Python Subject Code:4330701

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:
 Arithmetic Operator
 Relational Operator
 Logical Operator
 Bitwise Operator
 Assignment Operator
 Membership Operator
Arithmetic Operator

Prepared by: Department of Computer Engineering Page 5


Subject:Scripting Language –Python Subject Code:4330701

Bitwise Operator:

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

Prepared by: Department of Computer Engineering Page 6


Subject:Scripting Language –Python Subject Code:4330701

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

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

Prepared by: Department of Computer Engineering Page 8


Subject:Scripting Language –Python Subject Code:4330701

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

Prepared by: Department of Computer Engineering Page 9


Subject:Scripting Language –Python Subject Code:4330701

 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

Prepared by: Department of Computer Engineering Page 10


Subject:Scripting Language –Python Subject Code:4330701

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

Prepared by: Department of Computer Engineering Page 11


Subject:Scripting Language –Python Subject Code:4330701

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

Using Dictionary Mapping:


def monday():
return "monday"
def tuesday():
return "tuesday"
def wednesday():
return "wednesday"
def thursday():
return "thursday"
def friday():
return "friday"
def saturday():
return "saturday"
def sunday():
return "sunday"
def default():
return "Incorrect day"

Day = {
1: monday,
2: tuesday,
3: wednesday,
4: thursday,
5: friday,
6: saturday,
7: sunday
}

Prepared by: Department of Computer Engineering Page 12


Subject:Scripting Language –Python Subject Code:4330701

def DayName(dayofWeek):
return Day.get(dayofWeek,default)( )

print(DayName (3))
print(DayName (8))

Output:
Wednesday
Incorrect day

 First create different functions which return Day name.


 We create a dictionary in which stored different key-value pair.
 After that create main function which takes user input for finding day name.
 At last, called the function to print the desired output

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.

Prepared by: Department of Computer Engineering Page 13


Subject:Scripting Language –Python Subject Code:4330701

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

13. 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.
14. How to create a list. Explain append(),extend(),insert() and delete operations on list.

Prepared by: Department of Computer Engineering Page 14


Subject:Scripting Language –Python Subject Code:4330701

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


15. Write Characteristics of Tuple. Explain indexing and slicing in tuple.
Tuple: A tuple in Python is similar to a list.
Characteristics of Tuple:
 It is ordered.
 It allows duplicate members.
 It is immutable type(We cannot modify its element after it is created)
Prepared by: Department of Computer Engineering Page 15
Subject:Scripting Language –Python Subject Code:4330701

 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])

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)

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

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


difference)
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.
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))

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}
18. 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}

Prepared by: Department of Computer Engineering Page 18


Subject:Scripting Language –Python Subject Code:4330701

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

19. 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.
20. Give difference between User Define Function and Built in Function.

Prepared by: Department of Computer Engineering Page 19


Subject:Scripting Language –Python Subject Code:4330701

21. 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 of a recursive function to 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.

Example :

def factorial(x):

if x == 1:

return 1

else:

return (x * factorial(x-1))

calling a function:

Prepared by: Department of Computer Engineering Page 20


Subject:Scripting Language –Python Subject Code:4330701

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.

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

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

Prepared by: Department of Computer Engineering Page 21


Subject:Scripting Language –Python Subject Code:4330701

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)

Example: import random


a=[10,11,12,13,14]
print('before shuffle',a)
random.shuffle(a)
print('after shuffle',a)
Output:
before shuffle [10, 11, 12, 13, 14]
after shuffle [10, 12, 14, 11, 13]
24. 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))
Output: 5
pow():It receives two arguments, raises the first to the second and give result.
Example: import math
print(math.pow(2,4))
Output: 16.0

factorial(): It returns the factorial of a given number.


Example: import math
print(math.factorial(4))

Prepared by: Department of Computer Engineering Page 22


Subject:Scripting Language –Python Subject Code:4330701

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

Example:2 Get current date (Using date class)


import datetime Output
d=datetime.date.today()
print(d) 2022-11-28
26. 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:

Prepared by: Department of Computer Engineering Page 23


Subject:Scripting Language –Python Subject Code:4330701

from matplotlib import pyplot as plt


x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2]
plt.plot(x,y)
plt.show()

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.

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

Prepared by: Department of Computer Engineering Page 24


Subject:Scripting Language –Python Subject Code:4330701

 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]

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

Prepared by: Department of Computer Engineering Page 25


Subject:Scripting Language –Python Subject Code:4330701

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

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)

str="Hello World" Output


for s in str[::2]: HloWrd
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

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.

Prepared by: Department of Computer Engineering Page 27


Subject:Scripting Language –Python Subject Code:4330701

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

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

Prepared by: Department of Computer Engineering Page 28


Subject:Scripting Language –Python Subject Code:4330701

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

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

35. Explain write(),append() and writelines () for file with example.

Prepared by: Department of Computer Engineering Page 29


Subject:Scripting Language –Python Subject Code:4330701

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
f.close() text file.
append: 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.

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…

Prepared by: Department of Computer Engineering Page 30


VPMP Polytechnic, Gandhinagar
Department of Computer Engineering
Subject: Scripting Language-Python (4330701)

Semester: 3rd

Assignment: 1(Unit 1 Fundamentals of Python)

1. Give the difference between Scripting Language and Programming Language.


2. List and explain features of Python.
3. Write Application of python.
4. Explain basic structure of Python Program.
5. Explain keyword, identifier and variable.
6. Explain datatype with example.
7. Explain input and print method of python.
8. Explain type casting with example.
9. List out operator and explain bitwise operator.
VPMP Polytechnic, Gandhinagar
Department of Computer Engineering
Subject: Scripting Language-Python (4330701)

Semester: 3rd

Assignment: 2 (Unit 2 Control Flow Structures)

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


2. Explain while loop with flowchart, syntax and example.
3. Explain for loop and nested for loop with flowchart, syntax and example.
4. Explain switch case statement with flowchart, syntax and example.
5. Explain break, continue and pass statement with flowchart, syntax and example.
VPMP Polytechnic, Gandhinagar
Department of Computer Engineering
Subject: Scripting Language-Python (4330701)

Semester: 3rd

Assignment: 3 (Unit 3 Lists, Tuples, Sets and Dictionaries)

1. Define List. Write Characteristics of list.


2. How to create a list. Explain append(),extend(),insert() and delete operations on list.
3. Write Characteristics of Tuple. Explain indexing and slicing in tuple.
4. Write Characteristics of Set.
5. How python set is modified? Or Explain add(),update(),remove() and discard() method of
set.
6. Explain mathematical operations on Set(Union,Intersection,difference and symmetric
difference)
7. Write Characteristics of Dictionary. Explain operations on dictionary
(Accessing,changing,updating and removing)
VPMP Polytechnic, Gandhinagar
Department of Computer Engineering
Subject: Scripting Language-Python (4330701)

Semester: 3rd

Assignment: 4 (Unit 4 Functions and Modules)

1. Define function. Why do we need it?


2. Give difference between User Define Function and Built in Function.
3. What is Recursion? Explain with example.
4. What are modules in Python? Write Example of user defined module.
5. List out method of rand module. Explain any four with example.
6. Explain any five mathematical functions of math module.
7. Explain main classes of Date and Time module with one Example.
8. List out types of plots in Matplotlib. Explain any one with example.
9. What is package? How to Create and import package. Explain with example.
10. Write down steps for PIP Installation.
11. Write a program using the function to find maximum from two numbers.
12. Create a user defined function which prints square of all the even numbers between 1 to 5
13. Create a user defined function which will return the count of numbers divisible by 5 in
range 1 to 20.
VPMP Polytechnic, Gandhinagar
Department of Computer Engineering
Subject: Scripting Language-Python (4330701)

Semester: 3rd

Assignment: 5 (Unit 5 String Processing and File Handling)

1) Define String. How to create list of string.


2) How to use slicing operator for string. Explain with example.
3) Explain following function with example: isalnum( ), isalpha ( ), isdigit( ), isidentifier (),
islower(), isupper( ), and isspace( )
4) Explain following function with example: endswith(), startswith(), find(), rfind(), count() ,
5) List out Formatting function and explain any two.
6) Difference between Text files and Binary files:
7) Explain open() and close() for file with example.
8) Explain read(),readline() and readlines () for file with example.
9) Explain write(),append() and writelines () for file with example.
Seat No.: ________ Enrolment No.______________

GUJARAT TECHNOLOGICAL UNIVERSITY


Diploma Engineering – SEMESTER – 3 (NEW) – EXAMINATION – Winter-2022

Subject Code: 4330701 Date: 23-02-2023


Subject Name: Scripting Language -Python
Time: 02:30 PM TO 05:00 PM Total Marks: 70
Instructions:
1. Attempt all questions.
2. Make Suitable assumptions wherever necessary.
3. Figures to the right indicate full marks.
4. Use of programmable & Communication aids are strictly prohibited.
5. Use of non-programmable scientific calculator is permitted.
6. English version is authentic.

Marks
Q.1 (a) Explain if-elif-else control structure in Python. 03
પાયથોનમાાં if-elif-else નનયાંત્રણ માળખાં સમજાવો.
(b) Explain type casting in Python. 04
પાયથોનમાાં ટાઇપ કાન્ટાં ગ સમજાવો.
(c) Explain features of Python programming language. 07
પાયથોન પ્રોગ્રાનમાંગ ભાષાની લાક્ષનણકતાઓ સમજાવો.
OR
(c) Write a program to calculate simple and compound interest. 07
𝑃∗𝑅∗𝑇
Simple Interest= 100 and
𝑅 𝑁∗𝑇
Compound interest=𝑃 [(1 + 100∗𝑁) − 1]

Where P=Principal amount , R= rate of interest, T=Total duration,


N=number of times interest got compounded annually.
સાદ વ્યાજ અને ચક્રવૃનિ વ્યાજ ગણવા માટે નો પ્રોગ્રામ લખો.
𝑃∗𝑅∗𝑇
સાદ વ્યાજ= 100 અને
𝑅 𝑁∗𝑇
ચક્રવૃનિ વ્યાજ =𝑃 [(1 + 100∗𝑁) − 1]

Where P=મદ્દલ રકમ , R= વ્યાજદર, T=કલ સમયગાળો , N=વષષ મા કે ટલી


વાર ચક્રવૃનિ વ્યાજ ગણવામા આવ્ય.
Q.2 (a) Explain for loop with example. 03
ઉદાહરણ સાથે for લૂપ સમજાવો.
(b) Write a program to find the sum of following series: 04
1 1 1
1 + + + +. . . . . . . 𝑁 𝑡𝑒𝑟𝑚𝑠
3 5 7

નીચેની શ્રેણીનો સરવાળો શોધવા માટે પ્રોગ્રામ લખો:


1 1 1
1 + + + + ⋯ … . 𝑁 પદ સધી
3 5 7
(c) Write a program that find whether a given year is a leap year or not. 07
આપેલ વષષ લીપ વષષ છે કે નહીાં તે શોધવા માટે નો પ્રોગ્રામ લખો.
OR

1
Q.2 (a) List out different types of control statements in python and explain 03
any one.
પાયથોનમાાં નવનવધ પ્રકારના નનયાંત્રણ ્ટે ટમેન્ટની યાદી બનાવો અને
કોઈપણ એક સમજાવો.
(b) Write a program to print following pattern. 04
1
22
333
4444
55555
નીચે મજબની પેટનષ નપ્રાંટ કરવા માટે નો પ્રોગ્રામ લખો.
1
22
333
4444
55555
(c) Explain below string functions. 07
max, isalpha, islower, isspace, count, rfind and swapcase
નીચેના ્ટ્ ીાંગ ફાં ક્શન સમજાવો.
max, isalpha, islower, isspace, count, rfind and swapcase
Q.3 (a) Write a program to find the number of times an element occurs in the 03
list.
નલ્ટ મા કોઇ ઘટક કે ટલી વખત આવે છે તે શોધવા માટે નો પ્રોગ્રામ લખો.
(b) Differentiate between append() and extend() methods of list. 04
નલ્ટ ની append() અને extend() મેથડ વચ્ચેનો તફાવત લખો.
(c) Write an automated censor program that reads the text from a file and 07
creates a new file where all of the four-letter words have been replaced
by “****”.
્વયાંસાંચાનલત સેન્સર પ્રોગ્રામ લખો જે ફાઇલમાાંથી ટે ક્્ટ વાાંચે અને નવી
ફાઇલ બનાવે છે જ્ાાં ચાર-અક્ષરના બધા શબ્દો "****" દ્વારા બદલાય જાય.
OR
Q.3 (a) Write syntax of if-else and nested if-else. 03
if-else અને nested if-else ની નસાંટેક્ષ લખો.
(b) Explain basic tuple operations with example. 04
મૂળભૂત ટપલ ઓપરેશન્સ ઉદાહરણ સાથે સમજાવો.
(c) Write a program to randomly fill in 0s and 1s into a 4x4 2-dimension 07
list, print the list and find the rows and columns with the most
number of 1s.
એક એવો પ્રોગ્રામ લખો કે જે 4x4 નદ્વ-પનરમાણ નલ્ટમાાં રેન્ડમલી 0s અને 1s
ફીલ કરે, સૂનચ નપ્રાંટ કરે અને જે કોલમ અને રો મા સૌથી વધ 1 આવતા
હોઇ એવી રો અને કોલમ શોધી આપે.
Q.4 (a) Explain addition of an item and modification of existing item of 03
dictionary with example.
આઇટમનો ઉમેરો અને નડક્શનરીની હાલની આઇટમમાાં ફે રફાર ઉદાહરણ
સાથે સમજાવો.
(b) For the given set A={1,2,3,4,5} and B={10,2,3,4,50} match following 04
Statement with output.
Statement Output
A|B {1, 5}
A&B {1, 50, 5, 10}
A^B {1, 2, 3, 4, 5, 10, 50}
A-B {2, 3, 4}

2
આપેલ સેટ A={1,2,3,4,5} અને B={10,2,3,4,50} માટે નીચેના ્ટે ટમેન્ટ
સાથે આઉટપટ ના જોડકા જોડો.
્ટે ટમેન્ટ આઉટપટ
A|B {1, 5}
A&B {1, 50, 5, 10}
A^B {1, 2, 3, 4, 5, 10, 50}
A-B {2, 3, 4}
(c) Write a program to print Fibonacci sequence up to n numbers using 07
recursion.
નરકર્ષ નનો ઉપયોગ કરીને n નાંબર સધી નફબોનાકી નસક્વન્સ નપ્રન્ટ કરવા
માટે પ્રોગ્રામ લખો.
OR
Q.4 (a) List out functions of datetime module. 03
datetime મોડ્યલના ફાં ક્શન ની યાદી બનાવો.
(b) Write advantages of function in Python. 04
પાયથોનમાાં ફાં ક્શનના ફાયદા લખો.
(c) Explain the creation of user defined module and procedure to import 07
it in other program with example.
યર્ર નડફાઇન્ડ મોડ્યલની રચના અને તેને અન્ય પ્રોગ્રામમાાં ઇમ્પોટષ
કરવાની પ્રનક્રયા ઉદાહરણ સાથે સમજાવો.
Q.5 (a) Explain following functions. 03
(i) math.exp() (ii) math.floor() (iii) math.pow()
નીચેના ફાં ક્શન સમજાવો.
(i) math.exp() (ii) math.floor() (iii) math.pow()
(b) Write a program to plot sine wave using matplotlib. 04
matplotlib નો ઉપયોગ કરીને સાઈન વેવને પ્લોટ કરવા માટે એક પ્રોગ્રામ
લખો.
(c) List out various file accessing modes and explain each of them. 07
નવનવધ ફાઇલ એક્સેનસાંગ મોડ્સની યાદી બનાવો અને તેમાાંથી દરેકને
સમજાવો.
OR
Q.5 (a) List out functions for writing to file operation and explain each. 03
ફાઇલ ઑપરેશનમાાં લખવા માટે ના ફાં ક્શન ની સૂનચ બનાવો અને દરેકને
સમજાવો.
(b) Explain following string functions with example. 04
(i) endswith() (ii) find()
નીચેના ્ટ્ ીાંગ ફાં ક્શનો ઉદાહરણ સાથે સમજાવો.
(i) endswith() (ii) find()
(c) Write a program to read a date in the format DD/MM/YYYY and print 07
the same date in MM-DD-YYYY format.
DD/MM/YYYY ફોમેટમાાં તારીખ વાાંચવા માટે એક પ્રોગ્રામ લખો અને તે
જ તારીખ MM-DD-YYYY ફોમેટમાાં છાપો.

3
GUJARAT TECHNOLOGICAL UNIVERSITY
Program Name: Diploma in Engineering
Level: Diploma
Branch: Computer Engineering / Computer Science and Engineering
Course / Subject Code : DI02000101
Course / Subject Name : Scripting Language

W.E. F. Academic Year: 2024-2025

Semester: 2nd

Category of the Course: PCC

Prerequisite: Basic computer literacy, Logical Thinking and Basic Mathematics


Rationale: Python is an open-source, high-level programming language known for its
simplicity and versatility, making it one of the most popular languages worldwide.
Renowned for its straightforward syntax and extensive library ecosystem, Python
is used across a broad range of fields, including automation, server-side web
development, tools development, game programming, block chain, data science,
artificial intelligence, machine learning, and big data, among others. Its
accessibility makes it easy to learn, while its power and flexibility make it suitable
for diverse applications. This course is designed to teach the fundamentals of
Python programming, focusing on using core Python constructs to solve a variety
of problems. By the end of the course, students will be able to create simple
applications using Python, providing them with a strong foundation to explore
Python's advanced applications across these many domains.

Course Outcome:
After Completion of the Course, Student will able to:
No Course Outcomes RBT Level
Create and implement basic Python programs by utilizing suitable data types, Apply
01
constants, and literals.
Apply operators and control flow structures to design and implement solutions Apply
02
for the given problems.
Utilize data structures such as lists, tuples, sets, and dictionaries to develop Apply
03
efficient solutions for the given problems.
Apply Python's built-in functions, file handling features, and user-defined Apply
04
functions to develop effective solutions for the given problems.
05 Apply Python modules and packages to efficiently solve the given problems. Apply

*Revised Bloom’s Taxonomy (RBT)

w.e.f. 2024-25 http://syllabus.gtu.ac.in/ Page 1 of 6


GUJARAT TECHNOLOGICAL UNIVERSITY
Program Name: Diploma in Engineering
Level: Diploma
Branch: Computer Engineering / Computer Science and Engineering
Course / Subject Code : DI02000101
Course / Subject Name : Scripting Language

Teaching and Examination Scheme:


Total
Teaching Scheme
Credits Assessment Pattern and Marks
(in Hours)
L+T+ (PR/2) Total
Theory Tutorial / Practical Marks
L T PR C ESE PA / CA ESE
PA/CA (I)
(E) (M) (V)
3 0 2 4 70 30 20 30 150
Course Content:
Unit No. of % of
Content
No. Hours Weightage
Introduction and Syntax of Python Programming:
Introduction to Python, History of Python, Python Features, Python
Applications, Installing Python, Basic Structure of Python program,
Keywords and Identifiers, Variables, Type Casting, Input-Output
1. 07 15
functions: input, print, Data types: Number, String, Set, Tuple, List
and Dictionary, Declaration and use of data types, Literals,
Constants, Identifiers
Program Solving practice on the above concept
Operators and Control Flow Structures:
Basic Operators: Arithmetic, Logical, Comparison, Assignment,
Bitwise, Membership, Identity Operator, Python Operator
Precedence
2. Control Flow: Concept of Indentation and if, if...else, if…el 08 18
if…else statement with examples, While loop, for loop, range ()
function, break and continue, pass & return statements and Nesting
of loops
Program Solving practice on the above concept

w.e.f. 2024-25 http://syllabus.gtu.ac.in/ Page 2 of 6


GUJARAT TECHNOLOGICAL UNIVERSITY
Program Name: Diploma in Engineering
Level: Diploma
Branch: Computer Engineering / Computer Science and Engineering
Course / Subject Code : DI02000101
Course / Subject Name : Scripting Language

Data Structure in Python:


Lists: Defining Lists, accessing values in Lists, deleting values in
Lists, updating values in Lists, Basic List operations, Built in List
functions
Tuples: Defining Tuples, accessing values in Tuples, deleting
values in Tuples, updating values in Tuples, Basic Tuple
operations, Built in Tuple functions
3. 08 18
Sets: Defining Sets, accessing values in Sets, deleting values in
Sets, updating values in Sets, Basic Sets operations, Built in Sets
functions
Dictionaries: Defining Dictionary, accessing values in Dictionary,
deleting values in Dictionary, updating values in Dictionary, Basic
Dictionary operations, Built in Dictionary functions
Program Solving practice on the above concept
Python Functions and File Handling Functions
Built-in Functions – Type/ Data Conversion functions- int(),
float(), str(), bool(), list(), tuple(), dict(), set(), frozenset(), bytes(),
bytearray(), complex(), math functions- abs(), round(), pow(),
divmod(), sum(), min(), max() and String functions- len(), max(),
min(), isalnum(), isalpha(), isdigit(), isidentifier(), islower(),
isupper(), and isspace(), endswith(), startswith(), find(), rfind(),
count(), capitalize(), lower(), upper(), title(), swapcase(), replace(),
4. lstrip(), rstrip(), strip(), format(), center(), ljust(), rjust() 12 27
File handling Functions- read(), readline(), readlines(),Writing
functions: write(), append(), writelines()
User defined Functions: Introduction to Python User defined
Function, function definition, function calling, Passing parameters
to a function and returning values from a function, Recursion,
Scope of variables- Local variable and Global variable
Program Solving practice on the above concept

w.e.f. 2024-25 http://syllabus.gtu.ac.in/ Page 3 of 6


GUJARAT TECHNOLOGICAL UNIVERSITY
Program Name: Diploma in Engineering
Level: Diploma
Branch: Computer Engineering / Computer Science and Engineering
Course / Subject Code : DI02000101
Course / Subject Name : Scripting Language

Python Modules and Packages


Modules: Introduction to python module, Writing Module,
Importing Module , importing objects from module, Built-in
Modules- Numeric and Mathematic module
Packages: Introduction to Packages, Writing Packaging,
Matplotlib Package:- plot(),show(), xlabel(), ylabel(),grid(),bar(),
5. hist(), subplot(), pie(), savefig() 10 22
Numpy Package:- Creating Numpy arrays, Array attributes (shape,
ndim, size, dtype, itemsize), Array Initialization, indexing and
Slicing, Array Operations, Basic Numpy math and statistic
Function- np.sum(), np.min(), np.max(), np.mean(), np.std(),
np.var(), np.dot(), np.cross(), np.matmul()
Program Solving practice on the above concept
Total 45 100

Suggested Specification Table with Marks (Theory):


Distribution of Theory Marks (in %)
R Level U Level A Level N Level E Level C Level
12 16 42 0 0 0
Where R: Remember; U: Understanding; A: Application, N: Analyze and E: Evaluate C: Create (as
per Revised Bloom’s Taxonomy)

References/Suggested Learning Resources:


(a) Books:
1. Charles Dierbach, “Introduction to Computer Science Using Python: A Computational
Problem–Solving Focus”, John Wiley & Sons (25 January 2013), ISBN-10: 0470555157,
ISBN-13: 978-0470555156
2. John Zelle, “Python Programming: An Introduction to Computer Science”, Franklin, Beedle &
Associates Inc; Pap/Cdr edition (1 December 2003), ISBN-10 : 1590280288, ISBN-13 : 978-
1887902991
3. Liang Y. Daniel, “Introduction to Programming Using Python”, Pearson Education; First
edition (26 February 2017), ISBN-10: 9332551847, ISBN-13: 978-9332551848
4. R. Nageswara Rao, “Core Python Programming”, Dreamtech Press (1 September 2021), Delhi;
ISBN-10: 9390457157, ISBN-13: 978-9390457151
5. Paul Barry, “Head First Python”, Shroff/O'Reilly; Second edition (1 December 2016)., ISBN-
10: 9789352134823, ISBN-13: 978-9352134823

w.e.f. 2024-25 http://syllabus.gtu.ac.in/ Page 4 of 6


GUJARAT TECHNOLOGICAL UNIVERSITY
Program Name: Diploma in Engineering
Level: Diploma
Branch: Computer Engineering / Computer Science and Engineering
Course / Subject Code : DI02000101
Course / Subject Name : Scripting Language

6. Lutz M, “Learning Python”, Shroff; Fifth edition (1 January 2013), ISBN-10:7301152519,


ISBN-13:7301152519-799
(b) Open source software and website:
1. https://www.python.org
2. https://www.learnpython.org
3. https://www.python-course.eu
4. https://nptel.ac.in
5. https://www.youtube.com
6. https://www.edx.org
7. https://www.coursera.org/in
8. https://www.udemy.com
9. https://www.programiz.com/python-programming/online-compiler/
10. https://www.onlinegdb.com/online_python_compiler
11. https://www.online-python.com
Suggested Course Practical List:
1. Install and configure the Python environment. Run basic Python commands to verify the
Python environment.
2. Design and Test Python program to read your name, contact number, email, and birth-date and
print those details on the screen.
3. Design and Test Python Program to perform create access, update and delete operation on List,
Tuple, Sets and Dictionary.
4. Design and Test Python Program to demonstrate use of conditional statements: if, if...else,
if…elif…else statement.
5. Design and Test Python Program to demonstrate use of Operators: Arithmetic, Logical,
Comparison, Assignment, Bitwise, Membership and Identity Operator.
6. Design and Test Python Program to demonstrate use of looping statement: while, for, and
Nested loop.
7. Design and test a Python program using user defined function for given problem.
8. Design and Test Python Program to demonstrate use of math and string in-built functions.
9. Design and Test Python Program to demonstrate use of built in modules and user defined
modules.
10. Design and Test Python Program to demonstrate use of built in packages and user defined
packages.
11. Design and Test Python Program to demonstrate use of string processing functions.
12. Design and Test Python Program to demonstrate use of basic file functions.

w.e.f. 2024-25 http://syllabus.gtu.ac.in/ Page 5 of 6


GUJARAT TECHNOLOGICAL UNIVERSITY
Program Name: Diploma in Engineering
Level: Diploma
Branch: Computer Engineering / Computer Science and Engineering
Course / Subject Code : DI02000101
Course / Subject Name : Scripting Language

List of Laboratory/Learning Resources Required:


1. Computer with basic configuration with windows or unix os
2. Text Editor (VS Code, Sublime Text, Atom, Vim or any other editor) or Python IDE (IDLE,
PyCharm, PyDev, Spyder or any other IDE)
3. Python Interpreter (Versions: 3.6.x or higher)
4. Jupyter Notebook (Optional)

Suggested Project List:


1. Create a basic calculator application to practice functions and control structures.
2. Develop a number-guessing game using loops and conditional statements.
3. Create a system for managing books, including features for adding, updating, and deleting
records.
4. Create a program to plot sine and cosine waves using Matplotlib.
5. Use dictionaries and inheritance to manage employee details and calculate salaries.
6. Design an application to manage daily expenses, storing data in a file.
7. Create a program that uses modules to fetch and display weather data for a given location.
Suggested Activities for Students:
a) https://www.codechef.com/ , in this website very elementary programs are available, students
are expected to solve those programs
b) https://code.org/, an hour of coding event may be organized and students are encouraged to
participate.
c) Students are encouraged to register themselves in various MOOCs such as: Swayam, edx,
Coursera, Udemy etc to further enhance their learning.
d) Encourage students to participate in different coding competitions like Hackathon, online
competitions on codechef etc.
e) Encourage students to form a coding club at institute level.

w.e.f. 2024-25 http://syllabus.gtu.ac.in/ Page 6 of 6

You might also like