0% found this document useful (0 votes)
13 views31 pages

Question Bank With Answers For Unit1

Uploaded by

likithbas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views31 pages

Question Bank With Answers For Unit1

Uploaded by

likithbas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

1.

Write a short note on

a)Features of python

ANS

a)"Features of python. There are various reasons why python is having popularity programming
languages when compared with others. The following are some of important features of python.

1. Simple: Python is simple programning language when we read python .Programming


language,we feel like reading English hence developing &understanding programs will become
easy.
2. Easy to learn: Python uses very few key words . its program use very simple structure . Also
python reassemble 'C' language.Hence migrating from c' to python is easy
3. Open source:There is no need to pay for python software. Python can be freely available on
www.python.com!
4. High level language: Programming languages are of 2 types: High-level programming language
& low level programming language. A low level languages uses machine code instructions. High
level language uses english to develop programs like Cobol, PHP, JAVA, Python also use
English words in programming. Hence it is called high level programming language.
5. Dynamically type: In python, we need not declared any datatype. An assignment statement bind
the value of a name to an object. If a name is assigned to an object of I type it may later be
assigned to an object of different type. This is the meaning of saying python is dynamically typed

En: >>>a=10

>>> print (a)

10

>>>type (a)

<class lint'>

>>> b=10

>>> print (b)

10

>>> type (b)

<class 'int'>

>>>a= 10.1

>>>print (a)

10.1

>>>type (a)

<class 'float'>

>>>

6. Platform independent: When a python program is compiled using a Python compiler, it


generates byte Code. Python byte code represents a fixed set of instructions using Python virtual
machine we can run byte code instructions on any computer. We can use python on almost all os
like Unik, linux,windows, solaris, 0S-2, Amiga, AS400 etc.
7. Portable: When a program yields the same result on any computer in. the world, then it is called
as portable program. Python will give same result since they platform independent. Once a
python program is written, it can run on any computer using PVM.
8. Procedure and OOP: Python is a procedure oriented as well as object oriented programming
language.
 In procedure oriented Programing language, the Programs are built using functions &
procedures but in object oriented language the programs use class & object.
 A class "doesn't physically exist. A class is only an abstract idea which is represents
common behaviour of several objects.
 For example Dog' is a class, when we talk about Dog,, will have a picture in our mind
like head, body, legs, tail, etc. This imaginary picture is called class. when we take
Tommy, it will have all the features that we have in our mind but it exist physically.
Hence it is known as object. For a class, we can create any number of objects.
9. Interpreted: A program code is called source code. After writing a python program we should
compile the source code using python compiler. python Compiler translates the python program
into an intermediate code as byte code. This byte code is then executed by PVM. Inside PVM
byte code instruction is converted into machine code and produce result
10. Extensible: The program or piece of code return in C or ++ Can be integrated into python &
execute using PVM. So python program are extensible for other programs.
11. Huge library: Python has a big library which can be used on any Os. Programmers can develop
very easily by using python library
12. Scripting language: Scripting language is a programming language that doesn't use a compiler
for executing the source code rather it is using interpreter to translate source code into machine
code.
13. Database connectivity: Database represents software that stores and manupulate data. Python
provides interface to connect its program to a major databases like oracle, Sybase or MYSQL.

b)Flavours of python:

→ Flavours of python refers to different datatypes of python compilers. The following are some of them.

1. C-python: This is a standard python compiler implemented in c language. This python software
being downloaded directly from https://www.cPython.org. In this python program, initially
converted into byte code using c language. The advantage is that it is able to execute both C
programs &'C++' programs
2. Jython: This is early known as J-Python This is implementation of python program language
which is designed to run on java platform. This brytecode is executed by java virtual machine.
This can be downloaded from https://www.jpython.org'
3. Iron python : This is another implimentation, python program for 'dotnet'frame work. This is
written in C sharp (C#) language. The python program when compiled gives an intermediate
language which runs on "Common language runtime” (CLR) to produce the output. Iron
python can be downloaded from https://www.Ironpython.net.
4. Py Py: This is python implementation using python language. actually PyPy is written in a
language called 'rpython' which is created in python language. RPython is suitable for creating
language interpreter PYPY can be downloaded by. visiting The page https://www.PyPy.org
5. Ruby Python: This is a bridge between ruby and python interpreter. It encloses python
interpreter inside ruby application. This can be downloaded from 'https://rubygems
org/gems/ruby Python/version /0.6.3.
6. Stackless python : Small task which should run individually are called task- -lets. Tasklets run
independently on CPU and can communicate with other via channels.
 A thread is a process which can run 100's of such tasklets. These threads and tasklets
can be created in stacklese python without implementing stack .This can be downloaded
from "https://PyPi-Python.org/pypi/stackless Python/10.0.
7. Pythonxy: This is written as Python (x,y) which is implemented after adding scientific and
engineering related packages.This can be downloaded from
'https:// Pythonxy.github.io/downloads html’.
8. Anaconda Python:When python is redeveloped for handling large scale data processing
predictive analysis and scientific computation. It is called anaconda python. In this we can
develope python programs & R Programming language.

2. Explain about following with suitable example


a) Viewing byte code in python
b) Execution of python program

ANS: a)Viewing the byte code:

Let's consider the following program.

a=2

b=6

C = 2*6

print ("Result", c)

 we can type this program in text editor like Notepad and save program as first. py.It means
first.py file contains source code.Now compile the source code and the result is 12.
 Now we want to see bytecode instructions that were created internally by the python compiler.
To view the byte code, follow the procedure.
C:/>python-m dis first.py
 we are specifying 'dis' module which is used to display the list of programs.The output is
generated as below.

2 0 LOAD_CONST 0(10)

3 DUP_TOP

4 STORE_NAME 0(a)

7 STORE_NAME 1(b)

3 10 LOD_NAME 2(print)

13 LOAD_CONST 1('sum=')

16 LOAD_NAME 0(a)

19 LOAD_NAME 1(b)

22 BINARY_ADD

 The preceding byte code is displayed by 'dis' module which is known as 'dis assembler'
 The LOAD_NAME specifies byte code instructions as 2 arguments.
 The LOAD_Constant represent the string constant Binary-add instruction adds the previous
values.

b)Executing python programming:

 Gudio Van Rossum - Dutch scientist introduced Python in maths-cs in 1990 but public started
using in Feb 20 1991
 Python is the programming language that combines the features of "c' and `java'.
 Python was developed by Gudio Van Rossum at centre for mathematics and computer science in
1991 february 20
 Van Rossum picked the name "Python" from a TV show 'monty Python's flying circus.
 The logo of python shows two intertwisted stakes.

Execution:

 Lets assume we write a python program with a name first.py. Here first is known "source code"
using interpreter and `'.py' is the extension.
 Every python program is typed with extension '.Py'.
 The compiler (interpreter) converts the python program into byte code.
 Byte code represents a fixed set of instructions that represents all operation like arithmetic
operations, comparision operation, memory related operations etc which can run on any
operating system.
 The size of byte code instruction is one byte, and hence they are called with the name "byte
code”.
 These byte code instructions are contained in file “first.pyc".
 The next step is to run the program, if we give the byte code to the computer,it cannot run, it
cannot execute.
 Any computer can execute only binary code which have 0's & 1's. It is also known as machine
code.If it is necessary to convert the byte code into machine code, for this we use PVM.
 PVM uses an interpreter which understands the byte code and convert it into machine code.These
machine code instructions are executed by processor and results are displayed.
 An interpreter translates the source code line by line. The speed of interpreter is slow when
compared to compiler. To resolve this, PVM is added with JIT (JUST IN TIME) compiler.
 we compile python program, we cannot see '.pyc' files. This is done internally in the memory and
output is given. The reason is all the steps in the sequence source code → bytecode →
executable→output code are internally compiled and then final result is displayed.
 To separately create '.pyc' files,folow the procedure.
 Open command prompt, type python import compile py-compile.compile ("Program
name.py")
 In this command we are calling Python compiler which is going to generate byte code or '.pyc".

Example program

#python program for adding of two numbers

a=10

b=20

c=a+b

print(“sum is “,c)

step 1: save the program on desktop as first.py

step 2: to create byte code


import compile

3. Define
a) PVM
b) Comments and list out different types of comments with syntax and program

ANS: a)Python virtual machine:

 Computer can understand 0's & 1's which is known as machine code.
 We should convert into machine code before it is submitted to execution. For this we should use
compiler.
 A compiler normally converts programs source code into machine code.
 Each Python program, statement is converted into bytecode instructions.
 The size of each byte code is 1' byte. So it is known as bytecode instruction.We can find byte
code instruction ".pyc' shows the role of virtual machine converting bytecode instruction into
machine code.
 Python virtual machine is to convert byte code instruction into machine code so that computer
can execute machine code instructions & display final output.
 The interrupter converts byte code into machine Code & sends machine code to computer
processor for execution.
 PVM is also called as interpreter.

b)Comments:

 There are 2 types of comments:

1)single line comments

2) Multiline comments or double line comments.

 Single line comments:


1. These comments starts with #(Preprocessor)symbol.
2. # are useful to mention the entire line is treated as comment.

Ex: >>> # this Program belongs to comments.

>>> a=10 # value of a is 10

>>>#b=20

>>> print(b)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'b' is not defined.

>>>Print (a)

10

 Here the first line is starting with# and hence the entire line is treated as comment.
 In 2nd line a=10 is a statement. After this statement #symbol starts the comment describing
that the value is stored in variable 'a'. The part of this line from where # is started treated as
comment.
 Multiline comments:
1. When to make several lines as comments by using #instead we can use multiline comments.

>>>#this program

>>># is for

>>>#comments.

 The previous code can be written in triple double quotes or triple single quotes. in the
beginning & ending of the block.

>>>"""This is

. . . multiline

. . . comment"""

'this is \n multiline \n comment'

>>>'''This is

. . . multiline

. . . Comment'''

'This is \n multiline \n comment'

>>>

 The triple double quotes or triple single quotes are called multiline comments or block
comments. They are used to enclose a block of line as comment.

(Q)4. Explain about built in data types (None,numeric,Boolean) with suitable examples

ANS:
None
Datatypes -----------
Numeric

boolean

 A datatype represents type of data stored into variable or memory. The datatypes which are
already in python are known as builtin datatypes.

Builtin datatypes:
 There are 5 builtin datatypes type none, numeric, sequence, set, mapping
1. None:
 In python the none datatype represents an object that doesn't contain any value.
 In other languages, it is called as null object. In python program maximum of only 1 none
object is provided, when calling the function if no value is passed then the default value will
be taken as none where some value is passed to the function.

Ex:>>>x=None

>>> print(x)

None
>>> type (x)

<class 'None Type'>

>>>

2. Numeric type: The numeric type represents numbers there are 3 subtypes.
1. int:
 int represents integer numbers.
 An integer number is without decimals or fractions.

>>>a=-57

>>> Print (a)

-57

>>>type (a)

<clays 'int'>

 Here 'a' is called variable since it is storing -57 which is integer type. In python there is no limit
for size of integers.
2. Float: The float datatype represents the floating point number, a float number is a number that
contains decimal values.

>>>a=5.6923

>>> print (a)

5.6923

>>> type (a)

<class 'float'>

>>> b= 2.4e4

>>> print (b)

24000.0

>>>type (b)

<class 'float'>

 here 'a' is called float type variable and it is storing float values.
 floating point numbers can also be written in e or E to represent the power of 10.Here e or E
represents exponential.
 Here the float value 'b' represents

Example

b=2.4e4

>>> print(b)

24000.0

>>> type(b)
<class 'float'>

3. Complex numbers: A complex number is written in the form of a+bj or a-bj. Here 'a' represents
real part 'b'represents imaginary part. "j"' represents square root value of -1

>>> C1 = 2·5+2·5j;

>>> C2 = 3.5+3.5j

>>> C3= C1+C2

>>> print (C3)

>>> (6+6j)

>>>type (C1)

<class 'Complex'>

Representing binary, octal and hexadecimal

 Binary has base- 2 and represented as 0B or 0b.


 Octal has base -8 and represented 0o or 0O
 Hexadecimal has base - 16 and represented OX or Ox.

 Program for binary

>>>n=0b011o.

>>>print (n1)

>>type (n1)

<class 'int'>

 Program for octal

>>> nз= OXIC2

>>> print (n3)

450

>>>type (n3)

<Class int'>

 Program for hexadecimal

>>>Ex:>>>n2=0o15

>>> print (2)

13

>>> type (n1)

<class 'int'>
3. Bool datatype
 The bool datatype in Python represents boolean values.
 There are only two boolean values True or False that can be represented by this datatype. Python
internally is also represented as False. represents True as 1 and False as 0.
 A blank string like “ “ is also represented as False.
 Conditions will be evaluated internally to either True or False. For example,
a = 10

b = 20

if(a<b): print("Hello") # displays Hello.

 In the previous code, the condition a<b which is written after if - is evaluated to True and hence
it will execute print("Hello").
a = 10>5 # here 'a' is treated as bool type variable

print (a) # displays True

a = 5>10

print (a) # displays False

True + True will display 2 # True is 1 and false is 0

(Q)5.Discuss the differences between str, bytes, and bytearray data types in Python with example
program

ANS.

Sequences in Python

 Generally, a sequence represents a group of elements or items.


 For example a group of integer numbers will formasequence. There are six types of sequences in
python:
 str
 bytes
 bytearray
1. Str datatype
 In python,str represents string datatype.
 A string is represented by a groupo of characters.
 Strings are enclosed in single quotes or double quotes. Both are valid.
Str=”welcome” #here str is name of string type variable

Str=’welcome’ #here str is name of string type variable

 We can also write strings inside “””(triple double quotes) or ‘’’(triple double quotes)

strl = """This is a book on Python which


discusses all the topics of Core Python
in a very lucid manner."””
str2 = ‘’’This is a book on Python which
discusses all the topics of Core Python
in a very lucid manner.’’’
 The slice operator represents square brackets [and] to retrieve pieces of a string. Forexample, the
characters in a string are counted from 0 onwards.
 Hence, str[0] indicatesthe Oth character or beginning character in the string. See the examples
below
s = 'Welcome to Core Python' # this is the original string
print(s)
welcome to Core Python
print(s[0]) # display 0th character from s
W
print(s[3:7]) #display from 3rd to 6th characters
come
print(s[11:]) #display from 11th character onwards till end
core python
print(s[-1]) #display first character from the end
n
 The representation operator is denoted by ‘*’ symbol and useful to repeat the string for several
times. For example s*n repeats the string for n times.
Example:
Print(s*2)
Welcome to core pythonwelcome to core python
2. Bytes Datatype
 The bytes datatype represents a group of byte numbers just like an array does.
 A byte number is any positive integer from 0 to 255 (inclusive).
 Bytes array can store numbers in the range from 0 to 255 and it cannot even store
negative numbers.
 For example,elements = [10, 20, 0, 40, 15] # this is a list of byte numbers
x = bytes (elements) # convert the list into bytes array
print (x[0]) # display Oth element, i.e 10
 We cannot modify or edit any element in the bytes type array.
For example, x[0] = 55 gives an error.
 Here we are trying to replace 0th element (i.e. 10) by 55 which is not allowed.
#program to understand bytes type array
#create a list of byte numbers
Elements=[10,20,0,40,15]
#convert the list into bytes type array
x=bytes(elements)
#retrieve elements from x using for loop and display
for i in x : print(i)
output
10
20
0
40
15
3. bytearray Datatype
 The bytearray datatype is similar to bytes datatype.
 The difference is that the byte type array cannot be can be modified but the bytearray
type array can be modified.
 It means any element or all the elements of the bytearray type can be modified.
 To create a bytearray type array,we can use the function bytearray as:
elements =[10, 20, 0, 40, 15] # this is a list of byte numbers

x = bytearray(elements) print(x[0]) # convert the list into bytearray type array


print(x[0])

 We can modify or edit the elements of the bytearray. For example we can write
x[0] = 88
x[1] = 99

We will write program to create a bytearray type array and then modify the first two elements. Then we
will display all the elements using a for loop. This can be seen in Program .

 A Python program to create a bytearray type array and retrieve elements


# program to understand bytearray type array

# create a list of byte numbers

elements = [10, 20, 0, 40, 15]

# convert the list into bytearray type array

x=bytearray(elements)

#modify the first two elements of x

x[0]=88

x[1]=99

#retrieve elements from x using for loop and display

For i in x : print(i)

Output

88

99

40

15

6. Define list and show how the list is mutable with different programs

ANS.List

 A List represents group of elements.


 A Listcan store different types of elementswhichcanbemodified.
 Listaredynamic, whichmeanssizeisnot fixed.
 Difference between List and Array in C is, in List we can store different type of
databut inArrayonly similarkindofdatawe canstore.
 Python Lists are similar to arrays in C. However, the list can contain data of
differenttypes.
 The items stored in the list are separated with a comma (,) and enclosed
withinsquarebrackets [].
 We can use slice [:] operators to access the data of the list.
 The concatenationoperator (+) and repetition operator (*) works with the list in the
same way as theywereworkingwiththe strings.
ConsiderthefollowingPrograms

1.Lists in Python can be created by placing the sequence inside the square brackets[].

2. Checking type

3.print first and last element

4.ceating a list with strings

5.print first and last element of string

6. creating list with different elements

7.print first and last element of numeric and string


8. Creating list with range

Syntax

range(start, stop, stepsize)

 If the start is not mention it is assumed to be ‘0’ and stepsize is taken as 1,stop is one
element prior to ‘stop’.
Program :

9. Updating list

 Lists are mutable.It means we can modify the contents of list,append the list,update or
delete the elements in list
Program: #appending the list is adding elements to list at the end

10. Slicing in list : selecting from any index number to any index number
11. Removing elements from list: Deleting elements from the list

12. Reversing list elements(numerics)

Reversing list elements(strings)

 This will reverse the order of elements in the list.


13. Concatenation of two lists(numerics)

Strings

 Simply using “+”symbol operator on two lists to join. If write ‘x+y’,the list ‘y’ is added to
‘x’,if write ‘y+x’ , the list ‘x’ is added to ‘y’.
14. Repeation of list: Repeat the elements of a list ‘n’ number of times using ‘*’ operator.

15. Membership in list : If element is a member of a list or not by using ‘in’ and ‘not in’ operator.
If element is a member of the list,then in operator returns true else false.

16. Cloning or Aliasing list

 Giving new name to existing list is called aliasing

17. Methods to process list

1. len() – to find length of list elements

2. sum() – to find sum of list elements

3. index() – to find elements with index number

4. append() – to add a value to list at the end

5. insert() – to add value at required index

6. copy() – to copy elements

7. count() – to count number of times element is repeted

8. remove() – to remove element from list

9. pop() – remove elements one after other from end

10. sort() – putting elements in order


11. reverse() – changing the order of elements

12. clear() – to clear complete elements from list

Program

18. Nesting of list: List containing one more list in it is know as nesting

 With this we can say list is mutable where elements can be changed

7. What are
a) Constants in python with example program
b) Difference between c and python

ANSa) Constants in python with example program

b)Difference between c and python


8. What are
a) Identifiers and reserved words in Python with example program.
b) user defined data types
c) Doc String
9. Explain the naming conventions that should be followed when defining with suitable program

ANS:
Constanats: Constants name should be written in all capital letters. If a constant has several words, then
each word should be separated by an underscore (_)
Example program
# Constant name

MAX_RETRIES = 5

# Function name

def calculate_area(radius):

pi = 3.14159 # Variable name

return pi * radius * radius

# Class name

class Circle:

def __init__(self, radius):

self._radius = radius # Private variable name

# Method name

def get_area(self):

return calculate_area(self._radius)

10. Explain about


a) Tuple

ANS:
b) Dictionaries
c)set

You might also like