0% found this document useful (0 votes)
7 views10 pages

Terminal2 New 1

The document provides an overview of various Python programming concepts, including list manipulation methods like append, extend, and insert, as well as the use of range for generating sequences. It also covers nested tuples, set operations, script mode programming, data abstraction, for loops, input/output functions, types of functions, string operators, modules, conditional statements, and database management systems. Additionally, it discusses parameters in functions and linear search algorithms.

Uploaded by

yellowlotas
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)
7 views10 pages

Terminal2 New 1

The document provides an overview of various Python programming concepts, including list manipulation methods like append, extend, and insert, as well as the use of range for generating sequences. It also covers nested tuples, set operations, script mode programming, data abstraction, for loops, input/output functions, types of functions, string operators, modules, conditional statements, and database management systems. Additionally, it discusses parameters in functions and linear search algorithms.

Uploaded by

yellowlotas
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/ 10

1. What the different ways to insert an element in a list.

Explain with suitable example-(ch9)


i)append( ):function is used to add a single element to an existing list.
Syntax: list.append (element to be added)
Eg:
m=[3,4,5]
m.append(9)
print(m)
Output:
[3,4,5,9]
ii) extend( ): function is used to add more than one element to an existing list
multiple elements should be specified within square bracket as arguments of the function.
Syntax list.extend([elements to be added])
Eg:
m=[3,4,5]
m.extend([6,7)
print(m)
Output: [3,4,5,6,7]
iii) insert():function is used to insert an element at any position of a list.
Syntax: list.insert (position index, element)
m=[3,4,5]
m.insert(1,7)
print(m)
Output: [3,7,4,5]
2. What is the purpose of range()? Explain with an example.(ch9)
Used to generate a series of values in Python.
It has three arguments.
Syntax
range (start value, end value, step value)
start value – beginning value,default value is 0.
end value – upper limit of series.end till upperlimit– 1.
step value – used to generate different interval of values,it is optional.
for i in range(3):
print(i)
output
0
1
2
Creating a list with series of values
Used to create list with series of values.
list() function used to convert the range() as a list.
Syntax:
list_Variable = list ( range())
eg
m = list(range(3))
print(m)
[0,1,2]
List comprehensions
it is a simplest way of creating sequence of elements that satisfy a certain condition.
Syntax:
list = [ expression for variable in range ]
eg m = [ i+2 for i in range(3) ]
print (m)
Output:
[2,3,4]
3. What is nested tuple? Explain with an example.(ch9)
A tuple can be defined inside another tuple called Nested tuple.each tuple is considered as an
element.for loop is used to access all the elements in a nested tuple.
t = ((1,2), (3,4), (5,6))
for i in t:
print(i)
output:
(1,2)
(3,4)
(5,6)
4. Explain the different set operations supported by python with suitable
example(ch9) i)Union: It includes all elements from two or more sets
Operator |
function union()
Eg:
a={1,2,3}
b={3,4,5}
print(a|b)
print(a.union(b))
output
{1,2,3,4,5}
{1,2,3,4,5}
(ii) Intersection: It includes the common elements in two sets
Operator &
function intersection()
eg
a={1,2,3}
b={3,4,5}
print(a&b)
print(a.intersection(b))
output
{3}
{3}
(iii) Difference: It includes all elements that are in set A but not in the set B.
Operator -(minus)
function difference()
eg
a={1,2,3}
b={3,4,5}
print(a-b)
print(a.difference(b))
output
{1,2}
{1,2}
iv. Symmetric difference: It includes all the elements that are in two sets but not the one that are
common to two sets.
Operator ^(caret)
function symmetric_difference()
eg
a={1,2,}
b={3,4,5}
print(a^b)
print(a.symmetric_difference(b))
output
{1,2,4,5}
{1,2,4,5}

5. Describe in detail the procedure Script mode programming.(ch5)


A script is a text file containing the Python statements.
i) Creating Scripts in Python
*Choose File → New File or press Ctrl + N
*An untitled blank script text editor will be displayed
*Type any python code
ii) Saving Python Script
* Choose File → Save or Press Ctrl + S
*Save As dialog box appears on the screen
* Type the file name in File Name box.
* by default file will be saved with .py extension
* click Save button
iii) Executing Python Script
*Choose Run → Run Module or Press F5
*If your code has any error, it will be shown in red color in the IDLE window
*For the error free code, the output will appear in the IDLE window
6. How will you facilitate data abstraction. Explain it with suitable example(ch2)
To facilitate data abstraction we need to create two types of functions constructor, selector.
CONSTRUCTORS SELECTORS
Constructors are functions that build the Selectors are functions that
abstract data type. retrieve information from the data type
Constructors create an object, bundling Selectors extract individual pieces of
together different pieces of information. information from the object.
Ex. getname(city),
Ex. city=makecity(name,lat,lon) getlat(city),getlon(city)
city object will hold the city’s name, and these functions extract the information
its latitude and longitude. of the city object
7. Write a detail note on for loop in python(ch6)
The for loop is known as a definite loop,
the programmer knows exactly how many times the loop will be executed.
Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
in- is used to iterate over a sequence of objects,
sequence- is the collection of ordered or unordered values or even a string.
The control variable- accesses each item of the sequence in each iteration until it reaches the last
item in the sequence.
Example: flowchart
for i in range(3):
print(i)
output
0
1
2
The range() is a built-in function, to generate series of values between two numeric intervals.
syntax:
range (start,stop,[step])
start – refers to the initial value
stop – refers to the final value
step – refers to increment value,it is optional

8. Explain input() and print() functions with examples-(ch5)


The print() function: it is used to display result on the screen.
it evaluates the expression before printing it on the monitor.
Comma (,) is used to print more than one item.
syntax
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3” ……)
Example
print(“welcome”)
input() function
input( ) function is used to accept data as input at run time
syntax: Variable = input (“prompt string”)
* prompt string is a statement or message to the user, to know what input can be given..
*The input ( ) accepts all data as string but not as numbers.
*The int( ) function is used to convert string data as integer data explicitly.
Example
a=input(“enter name”)
b=int(input( “enter the age”))
9. Explain the different types of function with an example-ch7
User-defined functions -Functions defined by the users themselves.
Advantages:
1. Help us to divide a program into modules. So it is easier to manage.
2. It implements code reuse
3. Functions, allows to change functionality easily,
Syntax for User defined function
def<function_name ([parameter1, parameter2…])>:
<Block of Statements>
return <expression/None>
Function blocks begin with the keyword “def” followed by function name and parenthesis ().
parameters should be placed within these parentheses
The code block always comes after a colon (:) and is indented.
The statement return [expression] exits a function. return None - return with no arguments
eg
def fun():
print (“hello”)
fun()
Built-in functions- Functions that are inbuilt with in Python.
abs( ) returns an absolute value of a number. The argument may be an integer or floating
number Syntax: abs(x)
Example print( abs(-20)) Output:20
Lambda function- function that is defined without a name is called as lambda
function anonymous functions are defined using the lambda keyword.
anonymous functions are also called as lambda functions.
Syntax of Anonymous Functions
lambda[argument(s)]:expression
Example
s = lambda a:a
print (s(2))
Output:2
Recursion functions - Functions that calls itself is known as recursive.
The condition that is applied in any recursive function is known as base condition.
How it works: 1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion
import sys
sys.setrecursionlimit(1000)
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (5))
Output:120
10. Explain about string operators in python with suitable example-ch8
(i) Concatenation (+)
Joining of two or more strings is called as Concatenation. plus (+) operator is used to
concatenate strings
Example: print("welcome" + "python")
Output: welcomepython
(ii) Append (+ =)
Adding more strings at the end of an existing string is known as append.
operator += is used to append a new string with an existing string.
Example a="welcome"
a+="python"
print (a)
Output: welcomepython
(iii) Repeating (*)
The multiplication operator (*) is used to display a string in multiple number of times.
Example: print (“welcome”*2)
Output: welcomewelcome
(iv) String slicing
Slice is a substring of a main string.
A substring can be taken from the original string by using [ ] operator and index values. [ ] is also
known as slicing operator.
General format
str[start:end]
Where start is the beginning index and end is the last index value(n-1)
Example:
s=”welcome”
print(s[0:3])
Output: wel
(v) Stride when slicing string-
Third argument of slicing is called striding
which refers to the number of characters to move forward after the first character is retrieved
The default value of stride is 1.
Example:
s=”wel”
print(s[::-1])
output: lew
11. Write any Five Characteristics of Modules.
1. Modules contain instructions, processinglogic, and data.
2. Modules can be separately compiled and stored in a library.
3. Modules can be included in a program.
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by other modules.
12. Write a detail note on if..else..elif statement with suitable example.-ch6
we need to construct a chain of if statements then ‘elif ’ clause can be used instead of ‘if else’

Syntax
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
Eg statements-block n
if a>0:

print (“positive”)
elif a<0:
print (“negative”)
else:
print (“zero”)
13. Sys moduleThis module provides access to builtin variables used by the interpreter. Eg: argv
sys.argv is the list of command-line arguments passed to the Python program.
argv contains all the items that come via command-line input To use sys.argv,
import sys
sys.argv[0] contains the name of the python program sys.argv[1]is
the next argument passed to the program. main(sys.argv[1])
argv[1] c++ file name along with the path argv[0] contains the Python program
need not be passed because by default main contains python program
OS Module
provides a way of using operating system dependent functionality. It allows to interface with the
Windows operating system os.system():Execute the C++ compiling command in the shell g++
compiler is used to compile c++ program
syntax os.system(‘g++’+<variable_name1>+‘-<mode>’+<variable_name2>)
os.system- system() function defined in os module to interact with the windows operating system
g++ :- compiler to compile C++ program in Windows Operating system.
variable_name1:-Name of the C++ file along with the path without extension in string format
mode:-To specify input or output mode. Eg o prefixed with hyphen.
variable_name2:-Name of the executable file without extension in string format
eg: os.system('g++ '+cpp_file + '-o '+ exe_file) ‘+to concatenate all the string as a single string
getopt module helps to parse command-line arguments.
getopt.getopt() parses command-line options and parameter list.
syntax
<opts>,<args>=getopt.getopt(argv,options,[long_options])
opts contains list of splitted strings like mode and path
args contains error string, it will be empty if no error / argv This is the argument list to be parsed
options - it is a string to denote the mode (like ‘i’ or ‘o’)followed by a colon (:)
long_options –it is alist of strings.contain c++ file name with path and mode followed by an equal
sign ('=').
Eg: opts,args=getopt.getopt(argv,"i:",['ifile='])
14. Write in brief about SQLite and the steps used to use it.
SQLite is a simple relational database system, which saves its data in regular data files within internal
memory of the computer. It is designed to be embedded in applications, instead of using a separate
database server program such as MySQL or Oracle.
advantages
fast, rigorously tested, flexible and easy to work.
Step 1 import sqlite3
Step 2 create a connection using connect () method and pass the name of the database File
If the database already exists the connection will open .Otherwise, Python will
open a new database file with the specified name
Step 3 Set the cursor object cursor = connection. cursor ()
Cursor is a control structure used to traverse and fetch the records of the database.
All the commands will be executed using cursor object only.
sql_comm = "SQL statement"
execute() is used to execute the command and use the cursor method and pass the required sql
command as a parameter.
Many number of commands can be stored and can be executed one after other.
commit()- command is used to save the changes
close()-command is used to close the "Table connection".
15. Differentiate DBMS and RDBMS.
Basis of comparison DBMS RDBMS
Expansion Database Management System Relational DataBase Management System
Data storage Navigational model data by Relational model (in tables). ie data in tables as row
linked records and column
Data redundancy Exhibit Not Present
Normalization Not performed RDBMS uses normalization to reduce redundancy
Data Access Consumes more time Faster, compared toDBMS.
Keys and Index Does not use. used to establish relationship. Keys are used in
RDBMS.
Transaction Inefficient, Error prone and Efficient and secure.
management insecure.
Distributed Databases Not supported Supported by RDBMS.
Example Dbase, FoxPro. SQL server, Oracle, mysql, MariaDB, SQLite.
15.What are called Parameters and write a note on Parameter without Type & Parameter with Type
Parameters are the variables in a function definition
arguments are the values which are passed to function definition.
Parameter without Type
Example:
(requires: b>=0 )
(returns: a to the power of b) let rec pow a b:=
if b=0 then 1
else a * pow a (b-1)
require-precondition ,return-post condition.
Here data type is not mentioned . Some language compiler solves this type inference problem
algorithmically,
Parameter with Type
(requires: b>=0 )
(returns: a to the power of b ) let rec pow (a: int) (b: int) : int :=if b=0 then 1
else a * pow b (a-1)
in type annotations the parentheses are mandatory.
explicitly annotating the types help with debugging the type errors
16. Discuss about Linear search algorithm.
• Linear search also called sequential searchis a sequential method for finding a particular value in a
list.
• This method checks the search element with each element in sequence until the desired element is
found or the list isexhausted.
• In this searching algorithm, list need not be ordered.
Pseudo code:
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value of the list.
• If the values match, display the current index and value of the array
• If the values do not match, move on to the next array element.
. If no match is found, display the search element not found.
EX1: input: values[]={10,20,30,40,50}
Target=30
output=2
ex2: target=35 output=-1 if not found

17.Explain the Bubble sort algorithm withexample.


• it is a simple sorting algorithm.
• The algorithm is a comparison sort, is named for the way smaller elements "bubble" to the
top of the list.
• Although the algorithm is simple, it is too slow and less efficient.
Pseudo code: 1. Start with the first element i.e., index = 0,compare the current element with the next
element of the array.
2. If the current element is greater than thenext element of the array, swap them.
3. If the current element is less than the next or right side of the element, move to the next element.
Go to Step 1 and repeat until end of the index is reached.
Eg 15,10,12 15>10(swap)
10,15,12 15>12(swap)
10,12,15
18. Write the rules to be followed to format the data in a CSV file.
1. Each record is to be located on a separate line, delimited by a line break by
pressing enter key.
Eg roll,name
100,xxx
2. The last record in the file may or may not have an line break
Eg roll,name
100,xxx
3. The first line may be an optional header line
The number of header should contain the same number of fields
Eg 100,xxx
4. Fields are separated by commas.The last field must not be followed by a comma.
Eg roll,name
100,xxx
5. Each field may or may not be enclosed in double quotes. If fields have no double quotes,
then it will not appear inside the fields.
Eg “roll”,”name”
6. Fields containing line breaks , double quotes, and commas should be enclosed in double-
quotes.
Eg roll,name
100,”xxx,yyy”
7. If double-quote appearing inside a field must be preceded with another double quote.
Eg “””roll”””,name
100,xxx
19.Differentiate Excel file and CSV file.
Excel CSV
Excel is a binary file that include both CSV is a plain text format with a seriesof values
content and formatting separated by commas.

excel files can only be read by applications and CSV can be opened with any text editor eg
can only be written in the same way. notepad,MS Excel, OpenOffice,etc.
Excel save the file with extension .xls or xlsx CSV save the file with extension .csv
consumes more memory while importing data consumes less memory and importing is faster
20. Explain the various buttons in a matplotlibwindow.
Home Button:
help once you have begun navigating your chart.
return back to the original view,
Forward/Back buttons:
click these to move back to the previous point , or
forward again.
Pan Axis:
allows you to click it, and then click and drag your graph around.

Zoom: click and drag a square to zoom into specifically. Zooming in require a left click and drag. zoom out
with a right click and drag.
Configure Subplots: allow to configure variousspacing options with your figure and plot.
Save Figure:allow you to save your figurein various forms.
21. Features of Python over C++
• Python uses Automatic Garbage Collection whereas C++ does not.
• C++ is a statically typed language, while Python is a dynamically typed language.
• Python runs through an interpreter, while C++ is pre-compiled.
• Python code 5 to 10 times shorter than that written in C++.
• In Python, there is no need to declare types explicitly where as it should be done in C++
• In python function return multiple values Whereas in C++ function return only one value
22. Tabulate the different mode with its meaning.
'r' →Open a file for reading. (default)
'w'→ Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' →Open a file for exclusive creation. If the file already exists, the operation fails.
'a'→ Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't'→ Open in text mode. (default)
'b'→ Open in binary mode.
'+' →Open a file for updating (reading and writing)
23. CONSTRUCTOR AND DESTRUCTOR
Constructor is the special function .
It is automatically executed when an object of a class is created.
“init” which act as a Constructor.
It must begin and end with double underscore.
It can be defined with or without arguments.
This method is used to initialize the class variables.

General format of __init__ method (Constructor function)


def __init__(self, [args ……..]):
<statements>
Destructor is a special method to destroy the objects, _ _del_ _( ) method is used as destructor. It is
opposite to constructor. The __del__ method called automatically when we deleted the object reference
using the del
EXAMPLE
Class sample:
def __init__ (self):
print(“constructor”)
def __del__():
print(“destructor”)
s=sample()
del s
24. Explain the types of scopes for variable or LEGB rule with example.
The LEGB rule is used to decide the order in which the scopes are to be searched for scope resolution
Local(L)- Defined inside function/class
Enclosed(E)- Defined inside enclosing functions (Nested function concept)
Global(G)- Reserved names in built-in functions (modules)
Built-in(B)- Defined at the uppermost level
(i) Local scope:
• variables defined in current function.
• function will first look up for avariable name in its local scope if not outer scope is checked.
• Example:
Disp():
a:=7
Disp()
(ii) Global scope:
• A variable which is declared outside of allthe functions in a program is known as global
variable.
• it can be accessed inside or outside of all thefunctions in a program.
• Example
a:=10
Disp():
print a
Disp()
(iii) Enclosed scope:
• A variable which is declared inside a function which contains another function definition in it, the
inner function can also access the variable of the outer function.
• Example
Disp():
a:=10
Disp1():
print a
Disp1()
Disp()
(iv) Built-in scope:
• it is the widest scope
• Any variable or module which is defined in the library functions of a programming language
has Built-in or module scope.
• They loaded as soon as the library files are imported
• Example
Built in scope
Disp():
a:=10
Disp()
25. Write the different types of constraints and their functions.
Constraint is a condition applicable on a field or set of fields.
Type of Constraints: The different types of constraints are:
Unique Constraint, Primary Key Constraint, Default Constraint, Unique Constraint, Check Constraint
Unique Constraint
• ensures that no two rows have the same value in the specified columns.
Primary Key Constraint
• Primary key which helps to uniquely identify a record.
• only one field of a table can be set as primary key.
• does not allow NULL values
Default Constraint
• used to assign a default value for the field
• When no value is given automatically the default value will be assigned to the field.
Check Constraint
• helps to set a limit value placed for a field
• it allows only the restricted values on that field.
Column constraint: Apply only to individual column
Table constraint: apply to a group of one or more columns,it is given at the end of the table definition.
Example:
Create table Student (
admno integer not null unique,firstname char(20),Lastname char(20),class integer default 12,
age integer check(age <18),primay key(Firstname, Lastname)); → Table constraint
26. Write a python script to display all the records using fetchmany()(refer question book pg-305)
import sqlite3
cn=sqlite3.connect("Test.db")
c=cn.cursor()
c.execute("select * from item")
r=c.fetchmany(5)
print(r)

You might also like