0% found this document useful (0 votes)
14 views

CLASS XII CS VIVA

The document is a comprehensive review of Python, covering various topics such as IDLE, modes of operation, tokens, keywords, identifiers, variables, data types, operators, and error types. It also explains the differences between mutable and immutable types, comments, and various list operations. Additionally, it includes examples and comparisons of different Python functions and constructs.

Uploaded by

avnisinhalyra
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)
14 views

CLASS XII CS VIVA

The document is a comprehensive review of Python, covering various topics such as IDLE, modes of operation, tokens, keywords, identifiers, variables, data types, operators, and error types. It also explains the differences between mutable and immutable types, comments, and various list operations. Additionally, it includes examples and comparisons of different Python functions and constructs.

Uploaded by

avnisinhalyra
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/ 58

Review of Python | Vineeta Garg

REVIEW OF PYTHON
VIVA QUESTIONS

1. What does IDLE stand for? What is Python IDLE?

IDLE is an acronym of Integrated Development Environment and is the


standard, most popular Python development environment.

To run a program, we basically need an editor to write it, an interpreter/compiler


to execute it and a debugger to catch and remove the errors. Python IDLE provides
all these tools as a bundle. It lets edit, run, browse and debug Python Programs
from a single interface and makes it easy to write programs.

2. What is the difference between Interactive mode and Script mode?

Python IDLE can be used in two modes: Interactive mode and Script mode.
Python shell is an interactive interpreter. Python editor allows us to work
in script mode i.e. we can create and edit python source file.

3. What are tokens?


Tokens- Smallest individual unit of a program is called token. Example keywords,
identifiers, literals, operators and punctuators.

4. What are Keywords?


They are the words used by Python interpreter to recognize the structure of
program. As these words have specific meaning for interpreter, they cannot be used
for any other purpose.

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

NOTE: All these keywords are in small alphabets, except for False, None, True,
which are starting with capital alphabets.

5. What are identifiers and literals?


IDENTIFIERS: These are the names given to identify any memory block,
program unit or program objects, function, or module. Examples of identifiers are:
num, roll_no, name etc.

1
Review of Python | Vineeta Garg

LITERALS: A fixed numeric or non-numeric value is called a literal. Examples of


literals are: 502, -178.76, “Rajan” etc.

6. What is a variable?
Variables are like containers which are used to store the values for some input,
intermediate result of calculations or the final result of a mathematical operation
in computer memory.

7. What are the naming conventions of identifiers/variables/literals.


➢ Variable names are case sensitive. For eg. num and NUM are treated as two
different variable names.
➢ Keywords or words, which have special meaning, should not be used as the
variable names.
➢ Variable names should be short and meaningful.
➢ All variable names must begin with a letter or an underscore (_).
➢ After the first initial letter, variable names may contain letters and digits (0
to 9) and an underscore (_), but no spaces or special characters are allowed.
Examples of valid variable names: sum, marks1, first_name, _money

Examples of invalid variables names: marks%, 12grade, class, last-name

8. What do you understand by the terms L-value and R-value?


L-value is a value which has an address. Thus, all variables are l-values since
variables have addresses. As the name suggests l-value appears on left hand side
but it can appear on right hand side of an assignment operator(=). l-value often
represents as identifier.

R-value refers to data value that is stored at some address in memory. An r-


value is a value which is assigned to an l-value. An r-value appears on right but not
on left hand side of an assignment operator(=).

9. What is the default separator and terminator in print() function in


Python? How can we change it?

By default, print uses a single space as a separator and a \n as a terminator (appears


at the end of the string).
We can use the parameters sep and end to change the separator and terminator
respectively.

10.Compare and contrast list, tuple and dictionary.

List Tuple Dictionary

2
Review of Python | Vineeta Garg

A list is an ordered A tuple is an ordered A dictionary is an


collection of comma- collection of commas unordered collection of
separated values (items) separated values. items where each item is
within square brackets. The comma separated
a key: value pair. We can
values can be enclosed in
also refer to a dictionary
parenthesis but
as a mapping between a
parenthesis are not
set of keys/indices and a
mandatory.
set of values. The entire
dictionary is enclosed in
curly braces.

it is mutable it is immutable. it is mutable


list2=[“Raman”, 100, tup1=(‘Sunday’, dict1={'R':'RAINY' ,
200, 300, “Ashwin”] ‘Monday’, 10, 20)
'S':'SUMMER',
'W':'WINTER' ,
'A':'AUTUMN'}

11. What is the difference between mutable and immutable data types?

Mutable data types immutable data types


Variables of mutable data types can be
changed after creation and assignment Variables of immutable data types can
of values. not be changed or modified once they
are created and assigned the value. If an
attempt is made to change the value of
variable of immutable datatype, the new
is stored in some other memory location
and the variable starts pointing to that
location.

Some of the mutable data types in


Python are list and dictionary some of the immutable data types
are int, float, decimal, bool, string
and tuple.

12. What are the comments? Declare a single line comment and a multi-
line comment.
Comments are the line that compiler ignores to compile or execute. There are two
types of comments in Python

3
Review of Python | Vineeta Garg

• Single line comment: This type of comment deactivates only that line
where comment is applied. Single line comments are applied with the help of
“ #”. For e.g.

# This program calculates the sum of two numbers


>>>n1=10
>>>n2=20
>>>sum= n1 + n2 # sum of numbers 10 and 20
>>>print (“sum=”, sum)

• Multi line Comment: This Type of comment deactivates group of lines when
applied. This type of comments is applied with the help of triple quoted
string.

'''This is a
multiline comment'''

or

"""This is a
multiline comment"""

13. What are the different types of errors in a Python program?

SYNTAX ERROR: An error in the syntax of writing code that does not conform
to the syntax of the programming language is called a syntax error.
LOGICAL ERROR: It is an error in a program's source code that results in
incorrect or unexpected result. It is a type of runtime error that may simply
produce the wrong output or may cause a program to crash while running.
RUN TIME ERROR: A runtime error is an error that occurs during execution of
the program and causes abnormal termination of program.

14. Write functions for the following:

To convert string to int int()


To convert string to float float()
To convert numeric data to str()
string

15. What are operators?


Operators performs some action on data. Various types of operators are:
• Arithmetic (+,-,*,/,%)
• Assignment Operator (=)

4
Review of Python | Vineeta Garg

• Relational/comparison (<,>, <=,>=,==,!=)


• Logical (AND, OR, NOT)
• Identity Operators (is, is not)
• Membership Operators (in, not in)

16. What is difference between /, //, %?

/ // %
Divides two operands Integer division Divides two operands
and gives quotient and gives remainder
10/5=2 5//2=2 10%5=0
10/3.0 = 3.3 5.0//2=2.0
10.0/3=3.3
10/3=3

17. What is the difference between * and **?

* **
Multiplies two operands Exponentiation
10*5=50 2**4= 16

18.What is the difference between = and ==?

= ==
Assigns the value Checks if the value of left operand is
equal to the value of right operand, if
yes then condition becomes true.
x=50 15= = 15, true
16 = = 15, false

19. What is the difference between concatenation and repetition?


Concatenation (+) Repetition (*)
Joins the objects (strings, lists etc.) Concatenates multiple copies of the same
on either side of the operator object (strings, lists etc.) given number of
times
>>> str1="Tech" >>> str1*2
>>> str2="Era" 'TechTech'
>>> str1+str2
'TechEra'

>>> str3=str2+str1
5
Review of Python | Vineeta Garg

>>> print(str3)
EraTech

20. What is the difference between is and in operators?

is, is not - Identity Operators in, not in - Membership Operators


Identity operators are used to Membership operators are used to
compare two variables whether they validate the membership of a value. It
are of same type with the same tests for membership in a sequence,
memory location. such as strings, lists, or tuples.
The is operator evaluates to true if the The in operator is used to check if a
variables on either side of the operator value exists in a sequence or not.
point to the same memory location Evaluates to true if it finds a variable
and false otherwise. in the specified sequence and false
>>>x = 5 otherwise.
>>>type(x) is int >>>x = [1,2,3,4,5]
True >>>3 in x
True
The is not operator evaluates to true The not in operator evaluates to true
if the variables on either side of the if it does not find a variable in the
operator point to the different specified sequence and false
memory location and false otherwise. otherwise.
>>>x = 5 >>>x = [1,2,3,4,5]
>>>type(x) is not int >>>7 not in x
False True

21. What is the use of indentation in Python?


Indentation in Python is used to form block of statements also known as suite. It
is required for indicating what block of code, a statement belongs to. Indentation
is typically used in flow of control statements (like if, for etc.), function, class etc.
Although we can give any number of spaces for indentation but all the statements
in a block must have the same indent.
Unnecessary indentation results in syntax error and incorrect indentation results
in logical error.

22. What is the difference between indexing and slicing?


Indexing is used to retrieve an element from an ordered data type like string, list,
tuple etc. Slicing is used to retrieve a subset of values from an ordered data type.
A slice of a list is basically its sub-list.

23. What is the difference among insert, append and extend?

insert() append() extend()

6
Review of Python | Vineeta Garg

It is used to insert data It is used to add an is used to add one or


at the given index element at the end of the more element at the end
position. list. of the list.

z1=[121, "RAMESH", list1=[100, 200, 300, z1=[121, "RAMESH",


890, 453.90] 400, 500] 890, 453.90]
z1.insert(1, “KIRTI”) list2=[“Raman”, 100, z1.insert(1, “KIRTI”)
“Ashwin”] z1.append(10)
list1.extend(list2)
OUTPUT print(list1) print(z1)

[121, 'KABIR',
'RAMESH', 890, OUTPUT OUTPUT
453.9]
[100, 200, 300, 400, [121, 'KABIR',
500, 'Raman', 100, 'RAMESH', 890,
'Ashwin'] 453.9,10]

here list2 is added at the here list2 is added at the


end of the list list1. end of the list list1.

24. What is the difference among del, remove or pop methods to delete
elements from a List?

pop() del remove()


It removes the element The del method The remove method is
from the specified removes the specified used when the index
index, and also return element from the list, value is unknown and the
the element which was but it does not return element to be deleted is
removed. The last the deleted value. known.
element is deleted if no
index value is provided
in pop ( ).

>>> list1 =[100, 200, >>> list1=[100, 200, >>> list1=[100, 200,
90, 'Raman', 100, 'Raman', 100] 50, 400, 500,
'Ashwin'] >>> del list1[2] 'Raman', 100,
>>> print(list1) 'Ashwin']
>>> list1.pop(2)
>>> list1.remove(400)
OUTPUT >>> print(list1)
OUTPUT
90 [100, 200, 100] OUTPUT

7
Review of Python | Vineeta Garg

[100, 200, 50, 500,


'Raman', 100,
'Ashwin']

25. What are the major differences between key and value in a
dictionary?

key value
Keys are unique Values may not be unique
The keys must be of an immutable data The values of a dictionary can be of
any type
type such as strings, numbers, or
tuples.

26. Give the difference between upper() and isupper() functions of string.
The upper() function returns the copy of the string with all the letters in
uppercase. The isupper() function returns True if the string is in uppercase.
Example
>>> print(str3.upper())
ERATECH

>>> str5='tech era *2018*'


>>> print(str5.isupper())
False

27. Compare random(), randint() and randrange().

Function Purpose Example


name
random() Generates a random float number >>> random.random()
between 0.0 to 1.0. 0.21787519275240708

randint() Returns a random integer >>> random.randint(1,50)


between the specified integers. 21
>>> random.randint(1,50)
35

randrange() Returns a randomly selected >>> random.randrange(1,20)


element from the range created 1
by the start, stop and step >>>
random.randrange(1,20,5)
arguments. The value of start is 0

8
Review of Python | Vineeta Garg

by default. Similarly, the value of 16


step is 1 by default.

28. When is the else clause executed in looping statements?

The else clause in looping statements is executed when the loop terminates.

29. Compare break and continue.

BREAK CONTINUE

Break statement causes the Continue statement causes the current


loop to break/ terminate iteration of the loop to skip and go to the
immediately. next iteration.

The loop of which, break All the statements following the


statement is a part, stops. continue statement in the loop will not
be executed and loop control goes to the
next iteration.

s=10; s=10;
for i in range (10, 20, 3): for i in range (10, 20, 3):
s+=i s+=i
if(i==16): if(i==16):
break continue
print(s); print(s);
print("end"); print("end");

OUTPUT: OUTPUT:
20 20
33 33
end 68
end

9
Functions | Vineeta Garg

FUNCTIONS
VIVA QUESTIONS
1. What is a function?
Function is a named group of related programming statements which perform
a specific task. Functions are used to break the large code into smaller
manageable modules which are easy to manage and debug.
2. Need of functions
Some of the major advantages of using functions in a program are:

• Modularity: Functions provide modularity to a program. It is difficult


to manage large programs. Thus, a large program is usually broken down
into small units called functions. This makes the program easy to
understand, more organized and manageable.
• Code Reusability: Functions save space and time. Sometime a part
of the program code needs to be executed repeatedly. If this part of
program code is stored in a function than we do not need to write the
same code again and again. Instead, function can be called repeatedly.
This saves time and space. We can also store the frequently used
functions in the form of modules which can easily be imported in other
programs when needed.
• Easy debugging: It is easy to debug small units of a program than a
long program.

3. Types of functions
Basically, we can divide functions into the following three types:

• Built-in Functions
• Python Modules
• User-defined Functions

4. What is the difference between global and local variables?


A variable declared outside the function is known as global variable. The
global variable can be accessed inside or outside of the function.
A variable declared inside the function is known as local variable. The local
variable can be accessed only inside the function in which it is declared.

5. How can we access a global variable inside a function if a local


variable exists inside the function by the same name?

The keyword global may be used to access a global variable inside a function if
a local variable exists inside the function by the same name.

6. Consider the following set of statements:


Program 1 Program 2
x=9 x=9
def func(): def func():
1
Functions | Vineeta Garg

x=10 global x
print("x=",x) x=10
func() print("x=",x)
print(x) func()
print(x)

What will be the output of the above programs and why?

The output will be:

Program 1 Program 2
x= 10 x= 10
9 10

This is because in Python, variables that are only referenced inside a function
are implicitly global. If a variable is assigned a value or its value is modified
anywhere within the function’s body, it’s assumed to be a local unless explicitly
declared as global.

7. What is the difference between parameters and arguments?

Information can be passed to functions using parameters. They are specified


inside the parenthesis after the function name and are separated by a comma.
The values provided in the function call are called arguments.
Arguments and parameters have one to one correspondence.

8. What is the difference between Positional arguments and


Keyword/Named arguments?

When arguments are passed as positional arguments, the order in which the
arguments are sent or their position is very important.

• It is mandatory to pass arguments in the same order as the parameters.


• The arguments should have one to one correspondence/mapping with
parameters present in the function header.
• The number and type of arguments passed should match the number and
type of parameters present in the function header.

When arguments are passed as keyword arguments, the name of the argument
is given along with the value. In this case the position of arguments does not
matter. They can be written in random order.

9. What is wrong in the following function call?


test(a = 1, b = 2, c = 3, 4) #3

2
Functions | Vineeta Garg

Positional arguments cannot follow keyword arguments.

10. What is the purpose of a return statement? How can a function


return more than one value?
The return statement is used to return either a single value or multiple
values from a function. More than values are returned by a function in the
form of a tuple.

3
File Handling | Vineeta Garg

FILE HANDLING
VIVA QUESTIONS
1. What is the difference between files and variables of other data
types(like list, dictionary etc.) in terms of data storage ?
Variables store data in RAM which remains in memory as long as the program
is running and gets erased the moment our program gets over. This happens
because RAM is volatile in nature.
Files store the data on secondary storage devices like hard disk. The data stored
on secondary storage devices is permanent in nature and does not get erased
when the program gets over. When input/output operations are performed on
files data gets transferred from secondary storage to RAM and vice versa.

2. Compare Text, Binary and CSV files.

Text files Binary files CSV files


Text files are Binary files deal with CSV (Comma Separated
sequence of lines, non-text files such as Values) is a
where each line images or exe and store simple file format used
includes a sequence of data in binary format to store tabular data.
characters. All lines i.e. in the form of 0’s They are a convenient
are terminated by a and 1’s which is way to export data from
special character, understandable by the spreadsheets and
called the EOL or End machine. So when we databases as well as
of Line character. open the binary file in import or use it in other
Text files are stored in our machine, it decodes programs. These files are
human readable form the data and displays in a saved with the .csv file
and they can also be human-readable format. extension. In general, the
created using any text separator character is
editor. called a delimiter, and
other popular delimiters
include the tab (\t), colon
(:) and semi-colon (;)
characters.
Examples of text files Binary files can range
are: Web from image files like
standards: html, XML, JPEGs or GIFs,
CSS, JSON etc. audio files like MP3s
Source code: c, app, or binary document
js, py, java etc. formats like Word or
Documents: txt, tex, PDF.
RTF etc.

3. What is the difference between a and w modes?

1
File Handling | Vineeta Garg

'w' Open a file for writing. Creates a new file if it does not exist or
truncates the file if it exists.
'a' Open for appending at the end of the file without truncating it.
Creates a new file if it does not exist.

4. What is the difference in opening a file using open() function or


using with statement?

Using with ensures that all the resources allocated to file objects gets
deallocated automatically once we stop using the file.

5. What is the need of closing files?


Closing a file frees up the resources that were tied with the file. Before closing a
file, any material which is not written in file, is flushed off i.e., written to file.
So, it is a good practice to close the file once we have finished using it.

6. What is the difference between the write() and writelines() methods


used to write data in a file?

The write() function write a single string at a time and writelines() methods can
be used to write a sequence of strings.

7. What is the difference between the read() and readlines() methods


used to read data from a file?
The readline() method reads one line(i.e. till newline) at a time from a file and
returns that line. It reads the file till newline including the newline character.
The file is read sequentially from top i.e. first call to readline() method returns
first line, second call returns second line till end of file. The readline() method
returns an empty string when the end of file is reached.

The readlines()method reads the entire content of the file in one go and
returns a list of lines of the entire file. This method returns an empty value
when an end of file (EOF) is reached.

8. What is the purpose of read(n) method?


This method reads a string of size (here n) from the specified file and returns it.
If size parameter is not given or a negative value is specified as size, it reads and
returns up to the end of the file. At the end of the file, it returns an empty string.

9. What do you understand by the terms pickling and unpickling?


To store data in binary files, Pickle module is used. Pickle module is used to
store any kind of object in file as it allows us to store python objects with their
structure. Pickle module supports two major operations: Pickling and
Unpickling.

• Pickling is the process whereby a Python object is converted into a byte


stream.

2
File Handling | Vineeta Garg

• Unpickling is the process by which a byte stream is converted back into the
desired object.

The process of pickling and unpickling a Python data object is known as object
serialization.

10. Name the methods which are used to write and read into/form a
binary file.
The dump method of pickle module is used to write objects to binary file. The
load method of pickle module is used to read the object from the binary file.

11. Name two important functions of CSV module which are used for
reading and writing.
The two important functions of CSV module are:

csv.reader() returns a reader object which iterates over lines of a CSV file
returns a writer object that converts the user's data into a
csv.writer() delimited string. This string can later be used to write into CSV
files using the writerow() or the writerows() function.

3
Libraries | Vineeta Garg

PYTHON LIBRARIES
VIVA QUESTIONS

1. Why do we organize our code in the form of functions, modules and


libraries?
To easily access it and save ourselves from rewriting the same code again and
again. It also makes our code compact and easy to debug.

2. What is a relationship between module, package and library?

Module is a file which contains python functions, global variables etc. It is nothing
but .py file which has python executable code / statement.

Package is a collection of modules. Each package in Python is a directory


which MUST contain a special file called __init__.py. This file can be empty, and it
indicates that the directory it contains is a Python package, so it can be imported
the same way a module can be imported.

Library is a collection of packages. There is no difference between package and


python library conceptually. Some examples of library in Python are:

➢ Python standard library containing math module, cmath module, random


module, statistics module etc.
➢ NumPy library
➢ Matlplotlib library
➢ Tkinter library

Framework is a collection of libraries. This is the architecture of the program.

3. How do we create modules in Python?


Modules in Python are simply Python files with a .py extension. The name of the
module will be the name of the file. A Python module can have a set of functions,
classes or variables defined and implemented.

1
Libraries | Vineeta Garg

4. What is the difference between docstrings and comments?


Docstrings are similar to commenting, but they are enhanced, more logical, and
useful version of commenting. Docstrings act as documentation for the class,
module, and packages.

On the other hand, Comments are mainly used to explain non-obvious portions of
the code and can be useful for comments on Fixing bugs and tasks that are needed
to be done.

Docstrings are represented with opening and closing quotes while comments start
with a # at the beginning.

The comments cannot be accessed with the help function while docstring can be
accessed with the help function.

5. What are different ways of importing modules in Python?

import <module_name> - This import the entire module and all functions
inside that module can be used in our program.

import <module_name> as <alias_name> - An alias name can also be


given to a module. This alias name is used to invoke the functions stored inside
that module.

from <module_name> import <object_name> - This import only the


specified functions/objects. No other function/object besides the imported one can
be used in the program.

6. What is the importance of __init__.py file?

Each package in Python is a directory which MUST contain a special file


called __init__.py. This file can be empty, and it indicates that the directory it
contains is a Python package, so it can be imported the same way a module can be
imported.

2
Stacks | Vineeta Garg

STACKS
VIVA QUESTIONS
1. What is a stack? Give some real-life examples.

Stack is a data structure that provides temporary storage of data in such a way
that the element stored last will be retrieved first. This method is also called
LIFO – Last In First Out. In real life we can think of stack as a stack of
copies, stack of plates, stack of rotis etc.

2. Which function is used to push an element in stack?

The append() function.

3. Which function is used to pop an element in stack?

The pop() function

4. Which data structure is used to implement stacks in Python?

List

5. Give applications of stack.

The applications of stack are as follows:


• When a program executes, stack is used to store the return address at time
of function call. After the execution of the function is over, return address is
popped from stack and control is returned back to the calling function.
• Converting an infix expression to postfix operation and to evaluate the
postfix expression.
• Reversing an array, converting decimal number into binary number etc.

6. What do you mean by Overflow and Underflow in the context of


stacks?
Overflow: trying to insert more data when the size of the stack has reached its
maximum limit.
Underflow: trying to delete more data when the stack is empty.

1
MySQL | Vineeta Garg

MY SQL
VIVA QUESTIONS

1. What is DDL and DML?


DDL (Data Definition Language): All the commands which are used to create,
destroy, or restructure databases and tables come under this category. Examples
of DDL commands are - CREATE, DROP, ALTER.
DML (Data Manipulation Language): All the commands which are used to
manipulate data within tables come under this category. Examples of DML
commands are - INSERT, UPDATE, DELETE.

2. What is RDBMS?
RDBMS: A DBMS used to manage Relational Databases is called an RDBMS
(Relational Data Base Management System). Some popular RDBMS software
available are: Oracle, MySQL, Sybase, Ingress.

3. What is data inconsistency?


Data inconsistency occurs when same data present in two different tables does not
match.

4. What is a relation?
Relation/Table: A table refers to a two-dimensional representation of data
arranged in columns (also called fields or attributes) and rows (also called records
or tuples).

5. What is cardinality and degree?


Cardinality: Total number of rows in a table is called the cardinality of the table.
Arity/Degree: Total number of columns of a table is called the Degree of the
table.

6. What is the difference between primary key, candidate key and


alternate key?
Primary Key: The group of one or more columns used to uniquely identify each
row of a relation is called its Primary Key.
Candidate Key: A column or a group of columns which can be used as the
primary key of a relation is called a candidate key because it is one of the candidates
available to be the primary key of the relation.
Alternate Key: A candidate key of a table which is not made its primary key is
called its Alternate Key.

7. What is selection and projection?

1
MySQL | Vineeta Garg

The SELECTION operation is a horizontal subset of table/relation and is used to


choose the tuples(rows) from a relation that satisfies a given condition. It is
denoted by the symbol σ (sigma).
The PROJECTION operation is a horizontal subset of table/relation and used to
choose the attributes(columns) from a relation that are given in the attribute list.
It is denoted by the symbol ∏ (pi).

8. What are the different types of clauses used in where command?


CLAUSE/KEYWORD USAGE

DISTINCT Used to display distinct values (removes


duplicate values) from a column of a table.

WHERE Used to specify the condition based on


which rows of a table are displayed.

BETWEEN Used to define the range of values within


which the column values must fall to make a
condition true. Range includes both the upper
and the lower values.

IN Used to select values that match any value in a


list of specified values.

LIKE Used for pattern matching of string data


using wildcard characters % and _.

% (percentage): It is used to represent any


sequence of zero or more characters.
_ (underscore): It is used to represent a
single character.
IS NULL Used to select rows in which the specified
column is NULL (or is NOT NULL).

ORDER BY Used to display the selected rows in ascending


or in descending order of the specified
column/expression.

GROUP BY Group by clause is used when we need to


group the data of the table based on
certain type.

2
MySQL | Vineeta Garg

9. What is a cartesian product?


Cartesian product of two tables is a table obtained by pairing each row of one table
with each row of another table. The table obtained has
columns = sum of the columns of both the tables
rows = product of the rows of both the tables
It is represented by the symbol X.
10. What is a UNION?
Union of two tables is a table in which the number of columns is same as the
number of columns of the two tables and number of rows is the sum of the number
of rows of both the tables.
Union operation can be applied on two tables only if the tables have same number
and type of columns.

11. Give a command to insert a new column into a table? Alter table

12. Give a command to delete a column from a table? Alter table

13. Give a command to delete a row from a table? Delete from

14. Give a command to insert a new row into a table? Insert into

15. What is a difference between database and table?


Database is a collection of related tables
Table is a collection of related data in the form of rows and columns

16. What is the difference between update and alter command?


ALTER command is a Data Definition Language Command. UPDATE command is
a Data Manipulation Language Command.
ALTER Command add, delete, modify the attributes of the relations (tables) in the
database. UPDATE Command modifies one or more records in the relations.

17. What happens when the drop table command is executed?


All the records as well as the entire structure of the table is deleted.

18.In SQL can MAX function be applied to date and char type date?
Yes

19. What are aggregate functions?


Aggregate functions work on multiple rows. There are 5 types of aggregate
functions:

Aggregate function Purpose

MAX() To find the maximum value under


the specified column

3
MySQL | Vineeta Garg

MIN() To find the minimum value under


the specified column

AVG() To find the average of values under


the specified column

SUM() To find the sum of values under the


specified column

COUNT() To count the values under the


specified column

20. Difference between count() and count(*)


When the argument is a column name or an expression based on a column,
COUNT() returns the number of non-NULL values in that column.
If the argument is a *, then COUNT() counts the total number of rows satisfying
the condition, if any, in the table.
21. What is the purpose of group by clause?
Group by clause is used together with the SQL SELECT statement to group the data
of the table based on certain type. It arranges identical data into groups. It returns
only one single row for every grouped item.

22. What is the difference between where & having?


WHERE is used to put a condition on individual row of a table whereas HAVING
is used to put condition on individual group formed by GROUP BY clause in a
SELECT statement.
23. What is equi join?
When we extract data from two tables, they must have one column which is
present in both the tables. An equi join of two tables is obtained by putting an
equality condition on the Cartesian product of two tables.
This equality condition is put on the common column of the tables and is called
equi join condition.
24. What is a foreign key?
Foreign key is a column in one table which is the primary key of another table.
For eg. The column Deptno is the primary key of dept table and the foreign key of
emp table.
It is important that no entry should be made in the emp table in which deptno
does not belong to dept table ie we cannot write deptno in emp table which does
not exist in dept table.

4
Connectivity | Vineeta Garg

MySQL-PYTHON CONNECTIVITY
VIVA QUESTIONS

1. What is MySQL Connector/Python?


MySQL Connector/Python is a standardized database driver provided by MySQL.
It is used to access the MySQL database from Python.

2. What are the five major steps for connecting MySQL and Python?

There are five major steps for connecting MySQL and Python.

• Import MySQL connector


• Open a connection to a database
• Create a cursor object
• Execute a query
• Close the connection

3. How do we create a connection object?


Connection object is created with the help of connect() function. The connect()
function of mysql.connector package is used to establish a connection to MySQL
database. For example:

conn1 = mysql.connector.connect(host='localhost', database='test', user='root',


password='tiger')

Here, mysql.connector.connect is a MySQL-python library function that creates


the connection and returns a connection object, conn1. It connects to a specific
MySQL database (test in this case) using the given host (localhost in this case),
username (root in this case) and password (tiger in this case).

4. How do we create a cursor object?


The connection object returned by the connect() method is used to create
a cursor object. You can create a cursor object using the cursor() method of the
connection object/class. The cursor object is used to execute statements to perform
database operations. Foe example:

cursor1 = conn1.cursor()

Here, cursor1 is a cursor object created using connection object conn1 using
cursor() method.

1
Connectivity | Vineeta Garg

5. How do we execute SQL query through Python?


To execute SQL queries through Python, cursor object is used along with execute()
method. For example:

cursor1.execute("select * from emp;")

Here, cursor1 is a cursor object which uses execute method to run the SQL query.
The sql query is given in the form of a string. The output of the SQL query is stored
in the cursor object in the form of a result set.

6. What is the difference between fetchall() and fetchnone() methods?


The fetchall() method fetches all rows of a result set and returns a list of tuples.
The fetchnone() method returns a single record as a list/ tuple and None if no more
rows are available.

7. What is the purpose of rowcount parameter?


It returns the number of rows affected by the last execute method for the same cur
object.

2
VIVA QUESTIONS

Q1. What is Python?

Ans. Python is an open source, platform independent, high level and interpreted language.
Q2. Name two modes of Python.

Ans. Interactive Mode and Script Mode


Q3. Write Full Form of IDLE

Ans. Integrated Development Learning Environment


Q4. In which mode we get result immediately after executing the command?

Ans. Interactive mode


Q5. What do you mean by comments in Python?

Ans. Non executable lines are called Comments

Q6. Which symbols are used for single line comments and multiple line comments?

Ans. # symbol
Q7. What do you mean by variable?

Ans. Named storage location of value is called variable


Q8. Write code to find the address of variable ‘x’

Ans. id command is used to find the address of variable for example, to find the address of
variable ‘x’ code is
>>>id(x)
Q9. What do you mean by data type?

Ans. Data type refers to the type of value used for example integer, float string etc
Q10. Name five primitive data type in python.

Ans. Five primitive data types are : Numbers, String, List, Tuple and Dictionary

Q11. Which method is used to accept data from the user?

Ans. input( ) method


Q12. Write three numeric data type in python.

Ans. Integer, Floating Point and Complex


Q13. Name three sequential data types in python.
Ans. List, tuple and String
Q14. Which data type store the combination of real and imaginary numbers?

Ans. Complex
Q15. Write the output of the following:
>>> 4.7e7
>>> 3.9e2

Ans.
47000000
390

Q16. Write the output of the following :


1. >>> (75 > 2 **5)
2. >>> (25 != 5 *2)

Ans.
1. True
2. True
Q17. Write the code to display all keywords in python.

Ans import keyword print(keyword.kwlist)


Q18. Write the output of the following
>>> str = "Informatics"
>>>str[3] = 'e'
>>> print(str)

Ans. Type Error


Q19. What do you mean by Escape sequence?

Ans The sequence of characters after backslash is called escape sequence.


Q20. What is None data type?

Ans. This data type is used to define null value or no value.


for example
m = none, Now the variable ‘m’ is not pointing to any value, instead it is pointing to
none.

Q21. What do you mean by Operator?

Ans. Operators are special symbols which perform a special task on values or variables. Same
operator can behave differently on different data types.
Q22. What is the output of 2 % 5?

Ans. 2
Q23. What is the difference between ‘=’ and ‘==’ operator?

Ans. ‘ = ‘ is an assignment operator while ‘==’ is a comparison operator.


Q24. What is the difference between ‘a’ and “a” in python?

Ans. No difference as String can be enclosed in Single or Double quotes.


Q25. What is the difference between ‘/’ and ‘//’ operator?

Ans. Division operator(/) return the quotient in decimal while Floor Division Operator(//)
returns quotient as integer.
for example:
>>> 5 / 2 returns 2.5
>>> 5 // 2 returns 2

Q26. Give an example of infinite loop.

Ans.

while True:
print("A")

Q27. What is the purpose of break statement?

Ans. break statement is used to forcefully terminate the loop even the condition is True.
Q28. Write the output of the following :
>>> x = 8
>>> x = 5
>>> print (x + x)

Ans. 10
Q29. Identify the invalid variable names from the following and specify the reason also.

a) m_n
b) unit_day
c) 24Apple
d) #sum
e) for
f) s name

Ans.
24apple : Variable can not start with number
#sum : Variables can not start from special character.
for : Keyword can not be used as variable
s name : Spaces are not allowed in variable names
Q30. What do you mean by binary and unary operators? Give one example of each.

Ans. Binary operators work on two or more operands like Division (+), Multiplication (*).
2/3
4*3
Unary operators work only on one operand like Subtraction (-)
-9
-7

Q31. Write the name and purpose of the following operators.


//
%
**

Ans.

// : Name of Operator is Floor Division . It is used to find the integer part of the quotient
when one number is divided by other

% : Name is Modulus or Remainder Operator . It is used to find the remainder when one
number is divided by other

** : Name is Exponent. It is used to find the power of a number like 2**3 will give result 8.
Q32. What is the difference between eval() and int() function?

Ans. eval( ) function return error on passing integer argument while int( ) function does not
return error.
for example :
print(eval(12)) returns error
print(int(12)) returns 12
Q33. What is the difference between Lists and Tuples?

Ans.
Lists Tuples

List are mutable Not Mutable

Elements enclosed in Square brackets Elements enclosed in parenthesis

Q34. Write the code to reverse a list named L1.

Ans. L1.reverse( )
Q35. What is string in python?

Ans. Strings are contiguous series of characters enclosed in single or double quotes. Python
doesn’t have any separate data type for characters so they are represented as a single
character string.

Q36. What do you mean by Traversing String in Python?

Ans. It means accessing all the elements of the string one by one using index value.
Q37. What do you mean by Replicating String?
Ans. It refers to making multiple copies of same string.
Q38. What is String slicing?

Ans. String slicing is to get a piece of Substring from Main string.


Q39. What is the purpose of Try and Except in Python?

Ans. Try and Except are used in Error/Exception handling in Python. Code is executed in the
Try block and Except block is used to accept and handle all errors.
Q40. What is append( ) function in reference to list?

Ans. append( ) function simply add an element at the end of the list.

Q41. Can we print only keys of a dictionary?

Ans. Yes by using keys( ) method.


Q42. How can you print only keys of a dictionary without using keys( ) method?
d = {1 : “A”, 2 : “B”, 3 : “C”}

Ans.

d = {1 : "A", 2 : "B", 3 : "C"}


for i in d:
print(i)
Q43. What is the difference between actual argument and formal argument?

Ans. The values which are used in function call are called actual argument while the variables
used in function definition are called formal argument.
Q44. Name the four types of actual arguments in python.

Ans. The four types of actual arguments in python are:


1. Positional arguments
2. Default arguments
3. Keyword arguments
4. Variable length arguments
Q45. What is argument?

Ans. An argument is a value that is passed to the function when it is called.

Q46. What is the meaning of Scope of Variable?

Ans. Scope of variable refers to the part of program where it is accessible.


Q47. What is the difference between global and local variable?

Ans. Global variable can be accessed inside or outside the function while local variable can be
accessed only inside the function where it is declared.
Q48. What is Recursion?

Ans. Recursion is a method in which a function calls itself in its body.


Q49. Define module in python.

Ans. A module is a file which contains definition of various methods/functions.


Q50. Name any two built in module.

Ans. math module, random module and statistics module etc’

Q51. Which module is to be imported for sqrt( ), mean( ) and load()functions.

Ans. math module for sqrt( ), statistics module for mean( ) and pickle module for load( ).
Q52. What is the difference between Text file and Binary File.

Ans.
Text File Binary File

These files can be read by human directly These files can not be read by humans directly.

Each line is terminated by a special character ,


No delimiter for a line
known as EOL

Processing of file is slower than binary file Processing of file is faster than text file

Q53. Name the function which is used to open or close file in python.

Ans. open( ) function is used to open file while close( ) is used to close the file.
Q54. Name three modes of opening a file.

Ans. Read, Write and Append mode


Q55. What is the difference between read( ) and read(n) method?

Ans. read( ) method will read all content from the file while read(n) method will read first n
characters from file.

Q56. What is the difference between readline( ) and readlines() method?

Ans. readline() : This function will read one line at a time from the file
readlines() : This function is used to read all the lines from the file.
Q57. What does the readlines( ) method returns?

Ans. This method will return a list of strings, each separated by \n.
Q58. What is the difference between write( ) and writelines( ) method?

Ans. write(string) : This method takes a string as parameter and write the same string into our
file.
writelines() : This method is used for writing the sequence data type like list, tuple or string
into a file.
Q59. Expand FIFO.
Ans. First In First Out
Q60. Expand LIFO

Ans. Last In First Out

1. What is mysql connector?


2. What is cursor?
3. What does execute command?
4. Difference between fetchone fetchall?
5. What is prepared statement?
6. LIFO-Stack applications?
Undo, Redo, Prefix to postfix, expression evaluation ,FUNCTION CALLS, RECURSIVE
FUNCTIONS
7. STACK OPERATION EXPLAIN- PUSH POP
8. FIFO- QUEUES APPLICATION-PRINTER QUEUE,CPU SCHEDULING
9. QUEU OPERATION- ENQUEU, DEQUEUE
10. POSITIONAL ARGUMENTS IN FUNCTIONS
11. STACKS AND QUEUES ARE IMPLEMENTED USING ?
12. DEFAULT ARGUMENTS IN FUNCTIONS
13. DIFFERENCE BTW GLOBAL AND LOCAL VARIABLE
14. SCOPE OF VARIABLES
15. DIFF BTW ARGUMENT AND PARAMETERS
16. HOW MANY VALUES CAN BE RETURNED FROM A FUNCTIONS?
17. HOW CAN YOU RETURN MULTIPLE VALUES FROM A FUNCTION?
18. ACTUAL ARGUMENTS AND FORMAL ARGUMENTS?
19. If the content of the list is changed then what happens to its id?(It remains same)
20. If you alocate a list to another will the new list have new id?(Yes, even if name is same as assignment
creates a new list)
21. Ternary operator
22. What is id? (Address allotted to a variable?
23. What is a resultset? When we execute select query using cursor, the data is returned in an object
called result set.)

24. How can you access the result set? By using loop we fetch each record
25. What is None type?
26. Difference between text and binary files
27. Different modes of opening a file? Explain different modes
28. Difference between r,r+,rb(same for a and w)
29. Csv files-full form?
30. Method to open a file?
31. Extension of text , binary ,csv files?
32. What is the default mode of a file opened with open function?
33. Difference between append and write?
34. Which library should we import to work with binary files?
35. Dump function and syntax?
36. Load function and syntax
37. What do you mean by object in dump method?
38. Advantage of Binary files over text files? Fixed length records, fatser , Well structures
39. Why do we put try and except when we work with binary file?(As we have no idea how many records
are there in the file , it might lead to run time error as and when records end. So we handle it in
except. To avoid runtime error which is generated when we reach end of file(for same purpose we
use with clause with csv files)
40. What is EOFerror?
41. How do you close the file?
42. What is csv reader? What does it return?
43. Csv writer?
44. Library files for csv?
45. Write row?
46. File pointer? A reference which stores the address within a file to specify where the next read/write
operation will be performed

47. Tell()?
State some advantages of Python
Is Python an interpretated language?
What are Keywords?
What are iteration statements
What are selection statements
What are identifiers?
Difference between List and tuples
Use of Dictionary.
Concept of Bubble sort, Insertion sort, Selection sort.- Dry run on a given sample.
What are functions? Why are the advantages of the functions?
What are inbuilt functions?
what is the use of import keyword?
Can you create your own libraries?
Use of random functions.
. What are the key features of Python?
What are python modules? Name some commonly used built-in modules in Python?
What are local variables and global variables in Python?
.What is type conversion in Python?
Is indentation required in python?
How does break, continue and pass work?
What does [::-1} do?
What are python iterators?
How do you write comments in python?
How to comment multiple lines in python?
What is pickling and unpickling?
What is the purpose of is, not and in operators?
How can the ternary operators be used in python?
What do you understand by mutable and immutable types in python
Difference between random() and randint()
What are nested loops?
What are the different types of files?
what do you mean by file object
What are the parameters of open function .
How many values can a function return
Which statement helps to return values from a function
What is the role of file mode,
What are the different file modes(Basically you will be asked difference b/w any two li w and
w+, a and w,)
Difference between read(),readline(),readlines()
Use of close function
Difference between write and writelines
Use of flush function
How do you remove EOL character from the line read from the file.
what is stdin,stdout,stderr
What are relative file paths?
What are dump and load methods
Explain the process of pickling and unpickling
Tell and seek method- random examples can be given and asked about.
Full form of CSV
What are the two types of object of csv
writer/writerows/writerow() methods
In how many modes can you open a file
DO ALL THE OTQs from the book for data structures , file handling.

Linear and Binary Search concept


What are the prerequisites for performing Binary Search
What do you understand by linear datastructures
Name different Linear datastructures used in python
What do you mean by Stack ?
What is the meaning of term LIFO
Application of Stack
Read a lil about Queues too
Full form of DBMS
What is the difference between SQL and MySQL?
What are the different subsets of SQL?
What do you mean by DBMS? What are its different types?
What do you mean by table and field in SQL?
What are joins in SQL?
What is the difference between CHAR and VARCHAR datatype in SQL?
What is the Primary key?
What are Constraints?
What are tuples and attributes
What do you understand by cardinality and degree of the table
What are joins?
Q1. What is the difference between list and tuples in Python?

LIST vs TUPLES

LIST TUPLES

Lists are mutable i.e they can be Tuples are immutable (tuples are lists which
edited. can’t be edited).

Lists are slower than tuples. Tuples are faster than list.

Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)

Q2. What are the key features of Python?

• Python is an interpreted language. That means that, unlike languages


like C and its variants, Python does not need to be compiled before it is run.
Other interpreted languages include PHP and Ruby.
• Python is dynamically typed, this means that you don’t need to state the
types of variables when you declare them or anything like that. You can do
things like x=111 and then x="I'm a string" without error
• Python is well suited to object orientated programming in that it allows the
definition of classes along with composition and inheritance. Python does not
have access specifiers (like C++’s public, private).
• In Python, functions are first-class objects. This means that they can be
assigned to variables, returned from other functions and passed into
functions. Classes are also first class objects
• Writing Python code is quick but running it is often slower than compiled
languages. Fortunately,Python allows the inclusion of C-based extensions
so bottlenecks can be optimized away and often are. The numpy package is a
good example of this, it’s really quite quick because a lot of the number-
crunching it does isn’t actually done by Python
• Python finds use in many spheres – web applications, automation, scientific
modeling, big data applications and many more. It’s also often used as “glue”
code to get other languages and components to play nice.

Q3. What type of language is python? Programming or scripting?

Ans: Python is capable of scripting, but in general sense, it is considered as a


general-purpose programming language. To know more about Scripting, you can
refer to the Python Scripting Tutorial.

Q4.Python an interpreted language. Explain.

Ans: An interpreted language is any programming language which is not in machine-


level code before runtime. Therefore, Python is an interpreted language.
Q5.What is pep 8?

Ans: PEP stands for Python Enhancement Proposal. It is a set of rules that
specify how to format Python code for maximum readability.

Q6. How is memory managed in Python?

Ans: Memory is managed in Python in the following ways:

1. Memory management in python is managed by Python private heap space.


All Python objects and data structures are located in a private heap. The
programmer does not have access to this private heap. The python interpreter
takes care of this instead.
2. The allocation of heap space for Python objects is done by Python’s memory
manager. The core API gives access to some tools for the programmer to
code.
3. Python also has an inbuilt garbage collector, which recycles all the unused
memory and so that it can be made available to the heap space.

Q7. What is namespace in Python?

Ans: A namespace is a naming system used to make sure that names are unique to
avoid naming conflicts.

Q8. What is PYTHONPATH?

Ans: It is an environment variable which is used when a module is imported.


Whenever a module is imported, PYTHONPATH is also looked up to check for the
presence of the imported modules in various directories. The interpreter uses it to
determine which module to load.

Q9. What are python modules? Name some commonly used built-in
modules in Python?

Ans: Python modules are files containing Python code. This code can either be
functions classes or variables. A Python module is a .py file containing executable
code.

Some of the commonly used built-in modules are:

• os
• sys
• math
• random
• data time
• JSON

Q10.What are local variables and global variables in Python?


Global Variables:

Variables declared outside a function or in global space are called global variables.
These variables can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is known as a local variable. This variable is
present in the local space and not in the global space.

Example:

1 a=2
2 def add():
3 b=3
4 c=a+b
print(c)
5 add()
6
Output: 5

When you try to access the local variable outside the function add(), it will throw an
error.

Q11. Is python case sensitive?

Ans: Yes. Python is a case sensitive language.

Q12.What is type conversion in Python?

Ans: Type conversion refers to the conversion of one data type iinto another.

int() – converts any data type into integer type

float() – converts any data type into float type

ord() – converts characters into integer

hex() – converts integers to hexadecimal

oct() – converts integer to octal

tuple() – This function is used to convert to a tuple.

set() – This function returns the type after converting to set.

list() – This function is used to convert any data type to a list type.

dict() – This function is used to convert a tuple of order (key,value) into a dictionary.

str() – Used to convert integer into a string.


complex(real,imag) – This functionconverts real numbers to complex(real,imag)
number.

Q13. How to install Python on Windows?

Ans: To install Python on Windows, follow the below steps:

• Install python from this link: https://www.python.org/downloads/


• After this, install it on your PC. Look for the location where PYTHON has been
installed on your PC using the following command on your command prompt:
cmd python.

Q14. Is indentation required in python?

Ans: Indentation is necessary for Python. It specifies a block of code. All code within
loops, classes, functions, etc is specified within an indented block. It is usually done
using four space characters. If your code is not indented necessarily, it will not
execute accurately and will throw errors as well.

Q15. What is the difference between Python Arrays and lists?

Ans: Arrays and lists, in Python, have the same way of storing data. But, arrays can
hold only a single data type elements whereas lists can hold any data type elements.

Example:

1 import array as arr


2 My_Array=arr.array('i',[1,2,3,4])
3 My_list=[1,'abc',1.20]
4 print(My_Array)
print(My_list)
5
Output:

array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]

Q16. What are functions in Python?

Ans: A function is a block of code which is executed only when it is called. To define
a Python function, the def keyword is used.

Example:

def Newfunc():
1 print("Hi, Welcome to
2 Edureka")
3 Newfunc(); #calling the
function
Output: Hi, Welcome to Edureka

Q17.What is __init__?
Ans: __init__ is a method or constructor in Python. This method is automatically
called to allocate memory when a new object/ instance of a class is created. All
classes have the __init__ method.

Q18.What is a lambda function?

Ans: An anonymous function is known as a lambda function. This function can have
any number of parameters but, can have just one statement.

Example:

1 a = lambda x,y : x+y


2 print(a(5, 6))
Output: 11

Q19. What is self in Python?

Ans: Self is an instance or an object of a class. In Python, this is explicitly included


as the first parameter. However, this is not the case in Java where it’s optional. It
helps to differentiate between the methods and attributes of a class with local
variables.

The self variable in the init method refers to the newly created object while in other
methods, it refers to the object whose method was called.

Q20. How does break, continue and pass work?

Allows loop termination when some condition is met and


Break
the control is transferred to the next statement.
Allows skipping some part of a loop when some specific
Continue condition is met and the control is transferred to the
beginning of the loop
Used when you need some block of code syntactically, but
Pass you want to skip its execution. This is basically a null
operation. Nothing happens when this is executed.
Q21. What does [::-1] do?

Ans: [::-1] is used to reverse the order of an array or a sequence.


For example:
1 import array as arr
2 My_Array=arr.array('i',[1,2,3,4,5])
3 My_Array[::-1]
Output: array(‘i’, [5, 4, 3, 2, 1])

[::-1] reprints a reversed copy of ordered data structures such as an array or a list.
the original array or list remains unchanged.
Q22. How can you randomize the items of a list in place in Python?

Ans: Consider the example shown below:

1 from random import shuffle


x = ['Keep', 'The', 'Blue', 'Flag',
2 'Flying', 'High']
3 shuffle(x)
4 print(x)
The output of the following code is as below.

['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']


Q23. What are python iterators?

Ans: Iterators are objects which can be traversed though or iterated upon.

Q24. How can you generate random numbers in Python?

Ans: Random module is the standard module that is used to generate a random
number. The method is defined as:

1 import random
2 random.random
The statement random.random() method return the floating point number that is in
the range of [0, 1). The function generates random float numbers. The methods that
are used with the random class are the bound methods of the hidden instances. The
instances of the Random can be done to show the multi-threading programs that
creates a different instance of individual threads. The other random generators that
are used in this are:

1. randrange(a, b): it chooses an integer and define the range in-between [a, b).
It returns the elements by selecting it randomly from the range that is
specified. It doesn’t build a range object.
2. uniform(a, b): it chooses a floating point number that is defined in the range of
[a,b).Iyt returns the floating point number
3. normalvariate(mean, sdev): it is used for the normal distribution where the mu
is a mean and the sdev is a sigma that is used for standard deviation.
4. The Random class that is used and instantiated creates independent multiple
random number generators.

Q25. How do you write comments in python?

Ans: Comments in Python start with a # character. However, alternatively at times,


commenting is done using docstrings(strings enclosed within triple quotes).

Example:

#Comments in Python start like this


print("Comments in Python start with a #")
Output: Comments in Python start with a #
Q26. What is pickling and unpickling?

Ans: Pickle module accepts any Python object and converts it into a string
representation and dumps it into a file by using dump function, this process is called
pickling. While the process of retrieving original Python objects from the stored string
representation is called unpickling.

Q27. How will you capitalize the first letter of string?

Ans: In Python, the capitalize() method capitalizes the first letter of a string. If the
string already consists of a capital letter at the beginning, then, it returns the original
string.

Q28. How will you convert a string to all lowercase?

Ans: To convert a string to lowercase, lower() function can be used.

Example:

1 stg='ABCD'
2 print(stg.lower())
Output: abcd

Q29. How to comment multiple lines in python?

Ans: Multi-line comments appear in more than one line. All the lines to be
commented are to be prefixed by a #. You can also a very good shortcut method to
comment multiple lines. All you need to do is hold the ctrl key and left click in
every place wherever you want to include a # character and type a # just once. This
will comment all the lines where you introduced your cursor.

Q30.What are docstrings in Python?

Ans: Docstrings are not actually comments, but, they are documentation strings.
These docstrings are within triple quotes. They are not assigned to any variable and
therefore, at times, serve the purpose of comments as well.

Example:

1
"""
2 Using docstring as a comment.
3 This code divides 2 numbers
4 """
5 x=8
y=4
6 z=x/y
7 print(z)
8
Output: 2.0
Q31. What is the purpose of is, not and in operators?

Ans: Operators are special functions. They take one or more values and produce a
corresponding result.

is: returns true when 2 operands are true (Example: “a” is ‘a’)

not: returns the inverse of the boolean value

in: checks if some element is present in some sequence

Q32. What is the usage of help() and dir() function in Python?

Ans: Help() and dir() both functions are accessible from the Python interpreter and
used for viewing a consolidated dump of built-in functions.

1. Help() function: The help() function is used to display the documentation string
and also facilitates you to see the help related to modules, keywords,
attributes, etc.
2. Dir() function: The dir() function is used to display the defined symbols.

Q33. Whenever Python exits, why isn’t all the memory de-allocated?

Ans:

1. Whenever Python exits, especially those Python modules which are having
circular references to other objects or the objects that are referenced from the
global namespaces are not always de-allocated or freed.
2. It is impossible to de-allocate those portions of memory that are reserved by
the C library.
3. On exit, because of having its own efficient clean up mechanism, Python
would try to de-allocate/destroy every other object.

Q34. What is a dictionary in Python?

Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one


relationship between keys and values. Dictionaries contain pair of keys and their
corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, Capital & PM. Their
corresponding values are India, Delhi and Modi respectively.

1 dict={'Country':'India','Capital':'Delhi','PM':'Modi'}

1 print dict[Country]
India
1 print dict[Capital]
Delhi
1 print dict[PM]
Modi
Q35. What does this mean: *args, **kwargs? And why would we use
it?

Ans: We use *args when we aren’t sure how many arguments are going to be
passed to a function, or if we want to pass a stored list or tuple of arguments to a
function. **kwargs is used when we don’t know how many keyword arguments will
be passed to a function, or it can be used to pass the values of a dictionary as
keyword arguments. The identifiers args and kwargs are a convention, you could
also use *bob and **billy but that would not be wise.

Q36. What does len() do?

Ans: It is used to determine the length of a string, a list, an array, etc.

Example:

1 stg='ABCD'
2 len(stg)

Python Interview Questions


Q37. Explain split(), sub(), subn() methods of “re” module in Python.

Ans: To modify the strings, Python’s “re” module is providing 3 methods. They are:

• split() – uses a regex pattern to “split” a given string into a list.


• sub() – finds all substrings where the regex pattern matches and then replace
them with a different string
• subn() – it is similar to sub() and also returns the new string along with the no.
of replacements.

Q38. What are negative indexes and why are they used?

Ans: The sequences in Python are indexed and it consists of the positive as well as
negative numbers. The numbers that are positive uses ‘0’ that is uses as first index
and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index in
the sequence and ‘-2’ as the penultimate index and the sequence carries forward like
the positive number.

The negative index is used to remove any new-line spaces from the string and allow
the string to except the last character that is given as S[:-1]. The negative index is
also used to show the index to represent the string in correct order.
Q39. What are Python packages?

Ans: Python packages are namespaces containing multiple modules.

Q40.How can files be deleted in Python?

Ans: To delete a file in Python, you need to import the OS Module. After that, you
need to use the os.remove() function.

Example:

1 import os
2 os.remove("xyz.txt")
Q41. What are the built-in types of python?

Ans: Built-in types in Python are as follows –

• Integers
• Floating-point
• Complex numbers
• Strings
• Boolean
• Built-in functions

Q42. What advantages do NumPy arrays offer over (nested) Python


lists?

Ans:

1. Python’s lists are efficient general-purpose containers. They support (fairly)


efficient insertion, deletion, appending, and concatenation, and Python’s list
comprehensions make them easy to construct and manipulate.
2. They have certain limitations: they don’t support “vectorized” operations like
elementwise addition and multiplication, and the fact that they can contain
objects of differing types mean that Python must store type information for
every element, and must execute type dispatching code when operating on
each element.
3. NumPy is not just more efficient; it is also more convenient. You get a lot of
vector and matrix operations for free, which sometimes allow one to avoid
unnecessary work. And they are also efficiently implemented.
4. NumPy array is faster and You get a lot built in with NumPy, FFTs,
convolutions, fast searching, basic statistics, linear algebra, histograms, etc.

Q43. How to add values to a python array?

Ans: Elements can be added to an array using the append(), extend() and
the insert (i,x) functions.

Example:
1 a=arr.array('d', [1.1 , 2.1 ,3.1] )
2 a.append(3.4)
3 print(a)
4 a.extend([4.5,6.3,6.8])
5 print(a)
a.insert(2,3.8)
6 print(a)
7
Output:

array(‘d’, [1.1, 2.1, 3.1, 3.4])

array(‘d’, [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8])

array(‘d’, [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])

Q44. How to remove values to a python array?

Ans: Array elements can be removed using pop() or remove() method. The
difference between these two functions is that the former returns the deleted value
whereas the latter does not.

1 a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])


2 print(a.pop())
3 print(a.pop(3))
4 a.remove(1.1)
print(a)
5
Example:

Output:

4.6

3.1

array(‘d’, [2.2, 3.8, 3.7, 1.2])

Q45. Does Python have OOps concepts?

Ans: Python is an object-oriented programming language. This means that any


program can be solved in python by creating an object model. However, Python can
be treated as procedural as well as structural language.

Q46. What is the difference between deep and shallow copy?

Ans: Shallow copy is used when a new instance type gets created and it keeps the
values that are copied in the new instance. Shallow copy is used to copy the
reference pointers just like it copies the values. These references point to the original
objects and the changes made in any member of the class will also affect the original
copy of it. Shallow copy allows faster execution of the program and it depends on the
size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t
copy the reference pointers to the objects. It makes the reference to an object and
the new object that is pointed by some other object gets stored. The changes made
in the original copy won’t affect any other copy that uses the object. Deep copy
makes execution of the program slower due to making certain copies for each object
that is been called.

Q47. What is the process of compilation and linking in python?

Ans: The compiling and linking allows the new extensions to be compiled properly
without any error and the linking can be done only when it passes the compiled
procedure. If the dynamic loading is used then it depends on the style that is being
provided with the system. The python interpreter can be used to provide the dynamic
loading of the configuration setup files and will rebuild the interpreter.

The steps that are required in this as:

1. Create a file with any name and in any language that is supported by the
compiler of your system. For example file.c or file.cpp
2. Place this file in the Modules/ directory of the distribution which is getting
used.
3. Add a line in the file Setup.local that is present in the Modules/ directory.
4. Run the file using spam file.o
5. After a successful run of this rebuild the interpreter by using the make
command on the top-level directory.
6. If the file is changed then run rebuildMakefile by using the command as ‘make
Makefile’.

Q48. What are Python libraries? Name a few of them.

Python libraries are a collection of Python packages. Some of the majorly used
python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.

Q49. What is split used for?

The split() method is used to separate a given string in Python.

Example:

1 a="edureka python"
2 print(a.split())
Output: [‘edureka’, ‘python’]

Q50. How to import modules in python?


Modules can be imported using the import keyword. You can import modules in
three ways-

Example:

1 import array #importing using the original module name


2 import array as arr # importing using an alias name
3 from array import * #imports everything present in the array module

Basic Python Programs – Python Questions


Q51. Which one of these is floor division?

a) /
b) //
c) %
d) None of the mentioned
Answer: b) //

When both of the operands are integer then python chops out the fraction part and
gives you the round off value, to get the accurate answer use floor division. For ex,
5/2 = 2.5 but both of the operands are integer so answer of this expression in python
is 2. To get the 2.5 as the answer, use floor division using //. So, 5//2 = 2.5

Q52. What is the maximum possible length of an identifier?

a) 31 characters
b) 63 characters
c) 79 characters
d) None of the above

Answer: d) None of the above

Identifiers can be of any length.


Python Interface with MySQL with Answer Key
Class:-XII CS(083)
1. Write a MySQL connectivity program in Python to create a table TESTING
(ROLLNO integer, STNAME character(10)) in database TEST of MySQL and perform
The following:
i) Insert two records in it
ii) Display the contents of the table
Ans:- import pymysql
#Function to create Database as per users choice
def c_database():
try:
dname=input("Enter Database Name=")
c.execute("create database {}".format(dname))
c.execute("use {}".format(dname))
print("Database created successfully")
except Exception as a:
print("Database Error",a)
#Function to Drop Database as per users choice
def d_database():
try:
dname=input("Enter Database Name to be dropped=")
c.execute("drop database {}".format(dname))
print("Database deleted sucessfully")
except Exception as a:
print("Database Drop Error",a)
#Function to create Table
def c_table():
try:

c.execute('''create table testing


(
rollno integer,
stname char(20)
);
''')
print("Table created successfully")
except Exception as a:
print("Create Table Error",a)
#Function to Insert Data
def e_data():
try:
while True:
rno=int(input("Enter student rollno="))
name=input("Enter student name=")
c.execute("insert into testing values({},'{}')".format(rno,name))
choice=input("Do you want to add more record<y/n>=")
if choice in "Nn":
break
except Exception as a:
print("Insert Record Error",a)
#Function to Display Data
def d_data():
try:
c.execute("select * from testing")
data=c.fetchall()
for i in data:
print(i)
except Exception as a:
print("Display Record Error",a)
db=pymysql.connect(host="localhost",user="root",password="arxAZ5619&#1")
c=db.cursor()
while True:
print("MENU\n1. Create Database\n2. Drop Database \n3.Create Table\n4. Insert Record \n 5. Display
Entire Data\n 6.Exit")
choice=int(input("Enter your choice<1-6>="))
if choice==1:
c_database()
elif choice==2:
d_database()
elif choice==3:
c_table()
elif choice==4:
e_data()
elif choice==5:
d_data()
elif choice==6:
break
else:
print("Wrong option selected")

2. Write a MySQL connectivity program in Python to create a table named TESTING


(ROLLNO integer, STNAME character(10)) in database TEST1 of MySQL and perform
The following:
i) Insert two records in it
ii) Modify name of record having ROLLNO:1 to ‘PQR’
iii) Display the contents of the table
Ans:- import pymysql
#Function to create Database as per users choice
def c_database():
try:
dname=input("Enter Database Name=")
c.execute("create database {}".format(dname))
c.execute("use {}".format(dname))
print("Database created successfully")
except Exception as a:
print("Database Error",a)
#Function to Drop Database as per users choice
def d_database():
try:
dname=input("Enter Database Name to be dropped=")
c.execute("drop database {}".format(dname))
print("Database deleted sucessfully")
except Exception as a:
print("Database Drop Error",a)
#Function to create Table
def c_table():
try:

c.execute('''create table testing


(
rollno integer,
stname char(20)
);
''')
print("Table created successfully")
except Exception as a:
print("Create Table Error",a)
#Function to Insert Data
def e_data():
try:
while True:
rno=int(input("Enter student rollno="))
name=input("Enter student name=")
c.execute("insert into testing values({},'{}')".format(rno,name))
choice=input("Do you want to add more record<y/n>=")
if choice in "Nn":
break
except Exception as a:
print("Insert Record Error",a)
#Function to Display Data
def d_data():
try:
c.execute("select * from testing")
data=c.fetchall()
for i in data:
print(i)
except Exception as a:
print("Display Record Error",a)
#Function to Modify Data
def m_data():
try:
rno=int(input("Enter the roll whose name to be updated="))
c.execute("update testing set stname='PQR' where rollno={}".format(rno))
print("Data Upadted Sucessfully")
except Exception as a:
print("Display Record Error",a)
db=pymysql.connect(host="localhost",user="root",password="arxAZ5619&#1")
c=db.cursor()
while True:
print("MENU\n1. Create Database\n2. Drop Database \n3.Create Table\n4. Insert Record \n 5. Display
Entire Data\n 6. Modify Data\n 7.Exit")
choice=int(input("Enter your choice<1-7>="))
if choice==1:
c_database()
elif choice==2:
d_database()
elif choice==3:
c_table()
elif choice==4:
e_data()
elif choice==5:
d_data()
elif choice==6:
m_data()
elif choice==7:
break
else:
print("Wrong option selected")

3. Write a MySQL connectivity program in Python to create a table named TESTING


(ROLLNO integer, STNAME character(10)) in database TEST of MySQL and perform
The following:
i) Insert two records in it
ii) Delete the record of a particular student
iii) Display the contents of the table
Ans:- import pymysql
#Function to create Database as per users choice
def c_database():
try:
dname=input("Enter Database Name=")
c.execute("create database {}".format(dname))
c.execute("use {}".format(dname))
print("Database created successfully")
except Exception as a:
print("Database Error",a)
#Function to Drop Database as per users choice
def d_database():
try:
dname=input("Enter Database Name to be dropped=")
c.execute("drop database {}".format(dname))
print("Database deleted sucessfully")
except Exception as a:
print("Database Drop Error",a)
#Function to create Table
def c_table():
try:

c.execute('''create table testing


(
rollno integer,
stname char(20)
);
''')
print("Table created successfully")
except Exception as a:
print("Create Table Error",a)
#Function to Insert Data
def e_data():
try:
while True:
rno=int(input("Enter student rollno="))
name=input("Enter student name=")
c.execute("insert into testing values({},'{}')".format(rno,name))
choice=input("Do you want to add more record<y/n>=")
if choice in "Nn":
break
except Exception as a:
print("Insert Record Error",a)
#Function to Display Data
def d_data():
try:
c.execute("select * from testing")
data=c.fetchall()
for i in data:
print(i)
except Exception as a:
print("Display Record Error",a)
#Function to Modify Data
def del_data():
try:
rno=int(input("Enter the roll whose data you want to delete="))
c.execute("delete from testing where rollno={}".format(rno))
print("Data Deleted Sucessfully")
except Exception as a:
print("Delete Record Error",a)
db=pymysql.connect(host="localhost",user="root",password="arxAZ5619&#1")
c=db.cursor()
while True:
print("MENU\n1. Create Database\n2. Drop Database \n3.Create Table\n4. Insert Record \n 5. Display
Entire Data\n 6. Delete Data\n 7.Exit")
choice=int(input("Enter your choice<1-7>="))
if choice==1:
c_database()
elif choice==2:
d_database()
elif choice==3:
c_table()
elif choice==4:
e_data()
elif choice==5:
d_data()
elif choice==6:
del_data()
elif choice==7:
break
else:
print("Wrong option selected")

You might also like