You are on page 1of 16

UNIT-2

PYTHON INTERPRETER
Part-A
1. Define two modes of python?
 Python was two basic modes: Normal and Interactive
 Normal mode is the mode where the scripted and finished. Python files
are run in the python interpreter. This mode is also called as script
mode.
 Interactive mode is a command line shell which gives immediate
feedback for each statement, while running previously fed statement in
active memory. A new lines are fed into the interpreter, the fed program
as evaluated both in part and in whole.

2. Name the various operators in python?


 Python language support the following type of operator
 Arithmetic operator
 Comparison (Relational operator)
 Assignment operator
 Logical operator
 Bitwise operator
 Membership operator
 Identity operator

3. How do we use range in python?


 Range accepts an integer as the parameter and in this case, will pass it
11. The function, then starts at zero, and makes a list counting upwards
until it this one less than the number you put in. s0 here if we put in 11,
it will store the numbers 0-10 in the list number.
i. Numbers=range(11)
ii. Print (number)

4. Draw the diagram for flow the execution?


Main program

Execution Function
definition

Call Execution
flow

Return

Suspended
Execution

Execution

5. How to declare a global variable?


 Using the keyword global, you can reference the global variable inside a
function
 Variable “f” is global is scope and it’s assigned value |0| is printed in
output

6. What is the purpose of // and ** operators?


 Using // operator is used for performing the division operation. The
result will be rounded and only integer value of the result will be
displayed
 The operator ** is exponent operator. It calculates the power of given
number
For example
2**3=8

7. Explain membership operator?


 Python’s membership operators test for membership in a sequence. Such
as strings, list or tubles. There are two membership operator as
explained below

Operator Example
In X in Y
not in X not in Y

Part-B
1. Explain data type in python in details?
Data types:
i. Integer
ii. Float
iii. Boolean
iv. String
v. List

Integer and Float:

 A data type is a category for values and every value belongs to exactly
one data type. All data values in python are encapsulated in relevant
object classes. The most common data types in python are listed in
below.

Data type Example

Integers = -2,-1,0,1,2,3,4,5

Floating point number = -1.25,-1,0,-0.5,0.0,0.5,1.01

 The value -2 and 30 for example are said to be integer value. The integer
data types indicate values that are whole number. Numbers with a
decimal point, such as 2.14 are called floating point value 44.0 would be
floating point numbers

Example for integer Example for floats


>>>1+1 >>>c=2.1
2 >>>type(c)
>>>a=4 <type ‘float’>
>>>type (a)
< type ‘int’>

Boolean:
 Boolean is a data type named after George Boole (1815-1864). A
Boolean variable can take only two values True or False. The main of
this type is in logical expressions.
Example:
a= True
b= 30>45 #b gets the value false
 Boolean expressions are after used in conjunction with the if statement

Boolean operators:

 Boolean operations are performed using the AND, OR and NOT


keywords in python.
Example:
True AND False #False
False OR True #True
(30>45) OR (27<30) #True
Not True # False
Not (3>4) # True
 The operators follow some precedence rules which would make the
parentheses in the twiced line and last obsolute. Note then the operator
is implicity in the following Boolean expressions:

a<b<c #same as: a<b and b<c


a==b==c #same as: a==b and b==c

Example:

>>>3>4
False
>>>test= (3>4)
>>>test
False
>>>type (test)
<type ‘bool’>

Strings:

 Strings are amongst the most popular types in python and it is an


ordered sequence of the characters. We can create them simply by
enclosing character in quotes. Python treats single quotes the same as
double quotes. Creating strings is a simple as assigning values to a
variable
>>>spam= “That is Alice bird”

Characters:

 Python does not have a distinct character type. In python a character is a


string of length
 You can use the ord() builtin functions to convert from character to
integer and chr() builtin functions to convert from character integer to

Example:

a. The character “a” is a plain string of length 1:


>>> x=’a’
b. The integer equivalent of the letter “A”:
>>> x=”A”
>>> ord(x)
65

Operator of strings:

 The concatenated string with the “f” operation and create multiply
concatenated copies of a string with the “*”operator
 And augmented assignment (+=and*=) also work
Example:
>>> ‘horse’ + ‘and’+ ‘dog’
‘Horse and dog’
>>> “H”*40
‘#############’
>>>
>>>s1= ‘flower’
>>>s1+ =‘s’
>>>s1
‘Flower’

Lists:

 Python offers a range of compound data types often referred to as


sequences. List is one of the most frequently used and very versatile
data types and used in python. In python programming , a list is created
placing all the items (elements) inside a square bracket [ ], separated by
commas
 It can have any number of items and they may be of different types (
integer, float, string, etc)
#empty list
My-list = ( )
#list of integers
My-list= (1, 2, 3)
#list with mixed data types
My-list= (1, “world”, 3.4)
 Also , a list can over have another list as an item, this is called nested list
#nested list
My-list= (“horse”, (8, 4, 6), (a’))
 There are various way in which we can access the element of a list

2. Illustrate the concept of module in detail with example?

Modules:

 Modules are quite easy to create. They are simply python files, like your
regular scripts. To create a module, write one or more functions in a text
file. Then save it with a.py extension. Let’s do that now with an example
open up a new file your text editor or IDE, and make a function. I’m
going to continue with the example of a shopping card from earlies and
make a function to calculate tax on the products

1. Define add tax (price, tax)


2. New price = price/100*(100+tax)
3. Return new price
 If we save this file with a.py extension in the same directory as our
other script, we can use it as a module. It’s important to give it a
descriptive name so you know what it does when you come back later so
call this on Finance.py

Importing modules:

 To use modules, we can use either the import or from the keyword
import is the simplest and most common. So let’s try what first. You
then specify the name of the module, which is simply the file name,
without the .py extension. For example, with our finance module in the
same folder as our script we could write
 Import finance
Built-in modules:

 There are planty of built in module, just as there are with built in
functions. This is where python really excels. It takes what’s called the
batteries included approach.
 Because python has such an extensive range of built-in modular, there’s
no way to cover them all in one lesson. Some are quit obscure, and
there’s no print teaching a load of information you might never have a
use for instead. Let’s cover several of the most useful ones
i. Random
ii. Math
iii. Os
iv. Data time
v. Urllib2
1) Random:
 A good one to start with is random, because it’s easy to understand and
useful in most scripts you will write. As you expert this module lets you
generate random numbers. For example, when using python to create a
website. They can be used to making the password database more secure
or powering a random page feature. It we wanted a random integer, we
can use the randint function, like so
 Import random
 Print (random.randint(0,5))
2) Math
 The math module provides access to mathematical constant and
functions
1. Import math
2.
3. Math .pi# pi, 3.14….
4. Math .e # Euler’s number, 2, 71….
5.
6. Math. degrees (2) # 2 radians = 114.59 degrees
7. Math. Radians (60) # 60 degrees= 1.04 radians
8.
9. Math.sin (2) # sin of 2 radians
10. Math.cos(0.5) # cosine of 0.5 radians
11. Math.tan (0.23) #tangent of 0.23 radians
12.
13. Math. factorial (5) # 1*2*3*4*5=120
14. Math. Sqrt (49) #square root of 49=1
 There are lots more function in the modules, but these are some of the
most useful.
3) Data time:
 If you need to work with dates and times, then the data time modules is
your friend. This one is a very useful one to know about for web
development.
 Let’s import the module as useful
i. Import data time
4) Operating system (OS):
 The next module we are looking at is OS, which the underlying
operating system that python is running on be that windows, Mac or
Linux well focus on the path sub module
 These timestamps can be converted to useable string using the data time
module you can see how you can combine modules
1. From OS import path
2. Path.getsize ("user/giles/desktop/boot”)
#Return the size of a file in bytes-for this file
It was 314400 bytes, or 314kb
5) Urllib2:
 To finish our tour of python’s standard library, we’re going to have a
brief look at Urllib2. This module lets you interface with the web, so it’s
obviously quite relevant to us. The most useful function it provides it
urlopen, which downloads a page
 Import urllib2
 Urllib2,urlopen("http://net.in/python.com”)
 It can obviously swap the URL string for any site this will download the
HTML content of the page. This won’t return a string through so we
need to read data to get that out
 Import urllip2
 Urllip2,urlopen("http://net.infopython.com”).read(1
00)

3. Explain the concept of function in details?

Functions:

 A function is a normal contains for a block of code, there are two types
of functions. The ones that user defined function and x library
function/PREDEFIND function
Example:
01. #our two costs to add up
02. Cost 1=15
03. Cost2=20
04.
05.
06. Def sum cart();
07. Total cost=cost 1+cost 2
08. Print total cost
09.
10. Sum cart()

Arguments:

 An arguments is a way of passing data line into a function when we


don’t know which variable or variable that data is going to be in if that’s
confusing let’s table the example that I just referenced. We’ll add two
more costs: cost 3 and cost4

01. Cost 1=15


02. Cost 2=20
03. Cost 3=5
04. Cost 4=10
05.
06. Def sum cart (item 1, item2)
07. Total cost =item 1+ item 2
08. Print total cost
09.
10. Sum cart ( cost 1, cost2 )

Returning values:

01. Cost 1=15


02. Cost 2=20
03. Cost 3=5
04. Cost 4=10
05.
06. Def sum cart (item 1, item2)
07. Total cost =item 1+ item 2
08. Print total cost
09. Return total cost
10.
11. Cost 1= sum cart( cost1, cost2)
12. Cost 2= sum cart( cost3, cost4.
13.
14. Print (cart 1)
15. Print (cart 2)
 We need to provide python with a variable in which to store the answer,
and them we’re simply going to get that variable equal to our statement
calling the function, when the function returns a value, that values will
now be stored in the variable we specified

Function Built-in:

 There are some operators that are carried out often enough that python
has included them for use in any program. The way you call them is
exactly the same as calling your own, but you don’t have to define them
first

Str ():

 First, let’s look at one of the most useful function in python. The string
conversion function.
1. Number =10
2. Print (' The number is ‘ +number)

Len ():

 Another common task for strings is to be able to find the length of them
again. Python has a built in function for this. Let’s take the string ‘ Hello
word’ and try to find is length to need the built in len () function
1. String = “Hello word”
2. Print (len (string))

Int ():

 Moving on often you are given a number like 10.6 or 3.396, which is not
an integer, but you need an integer from them the built in function to
convert to an integer is called int () function
1. Number =10.6
2. Print (int (number))

Range ():

 Range accept an integer as the parameter and in this case, we’ll pass it
11. The function, then starts at zero, and makes a list counting upwards
until it less then the number you put in. so were if we put in 11 it will
store the numbers 0-10 in the list numbers
1. Number = range (11)
2. Print ( number )

Definitions and uses:

 Pulling together the code fragments from the previous section the whole
program looks like this
Def print_lyrics();
Print (“I’m a number jack, and I’m okay.”)
Print (“I sleep all night and I work all day.”)
Def repeat_lyrics ();
Print_lyrics ()
Print_lyrics ()
repeat_lyrics ()

4. Explain about flow of execution and parameter arguments details?

Flow of execution:

 The order of statements that execute in python is called floe of execution


 The statement execute sequentially one after the other from top to
bottom
 The statement inside the function gets executed only when the call to
that function is ex encountered
 During program execution if a call to some function is encountered
definition , the statement inside the function definition get executed
sequentially and finally the control is returned to the next statement
from where it is left illustrates the flow of execution in python.

Parameter and Arguments:

 Some of the functions we have seen require arguments for example.


When call math, sin, it pass a number as an argument. Some function
take more than one arguments: math.pow takes two the bases and the
exponent
 Inside the function the arguments are assigned to variables called
parameter
Def print_twice (flower)
Print (flower)
Print (flower)
 The function words with any value that can be printed
>>>print_twice (‘world’)
Word
Word
>>>print_twice (56)
56
>>>print_twice (math,pi)
3.14159265359
3.14159265359
 The same rules of composition that apply to built in function also apply
to user defined function kind of expression as an argument for
print_twice
>>>print_twice (‘spam’ * 4)
spam spam spam spam
spam spam spam spam
>>>print_twice (math.coslmath.pi)
-1.0
-1.0
 The argument is evaluated before the function is called example the
expression ‘spam’ * 4 math.cos (math.pi) only evaluated once
 You can also use a variable as an arguments
>>>book = ‘python’
>>>print_twice (book)
Python
Python
 The name of the variable we pass as an argument has nothing the name
of the parameter it doesn’t matter here print_twice we call everybody
bruce

5. Write program?
i. To circulate value of n variable

Program:

a=[1, 2, 3, 4]
a[1:]+a[:1]
a=[1, 2, 3, 4]
a[2:]+a[:2]
a=[1, 2, 3, 4]
a[3:]+a[:3]
def circulate (a, n);
return a [n:1]+a[1:n]
Output:

>>>leap (2012)
is a leap_year
>>>leap (2017)
Is a not leap year
ii. Find distance between two points

Dist=√(𝑿𝑨 − 𝑿𝑩)𝟐 + (𝒀𝑨 − 𝒀𝑩)𝟐

For example:

Y
A (9,7)

B (3,2)

dist =√(𝟗 − 𝟑)𝟐 + (𝟕 − 𝟐)𝟐


=√𝟔𝟐 + 𝟓𝟐
=√𝟔𝟏
=7.8102

Import math
Print (“enter value of x1”)
x1 = int (input ())
Print (“enter value of x2”)
X2 = int (input ())
Print (“enter value of y1”)
y1 = int (input ())
Print (“enter value of y2”)
y2 = int (input ())
dist = math.sqrt ((x2-x1)**2+(y2-y1)**2)
print (“The distance between two point is,”dist)

6. Precedence of operator?
 In this python we are going to look at operation precedence in python.
We will be focusing on the operators we have already learned like **, *,
1, //, %, + and -. It is important to understand what operator will run first

Operator precedence:
 The list below will show which operator has more procedure over the
operators. So the first operation in the list will run before the second
operator below

Rank Operator Meaning


1 ** Exponent
2 *, /, %, // Multiplication, true division, module
floor division. In this case if these
operators where in the same equation
then the equation would run left to
right

3 +, - Addition and subtraction are last


operators to run

Operator precedence examples:


 Let’s look at some examples and figure out which operator will run in
the equation. The order in which the operator run could have some
serious effects on your result.

Exponent and multiplication:


 Exponent will always run before the multiplication equation. Take a
look at the example
#Exponent and multiplication
#Exponent runs first
>>>2**4+2
18
>>>if
Multiplication ran first this answer would be 16
>>2*4**2
32

Exponent and division:


 Exponent will always run before s division equation
Example:
#Exponent and division
#Exponent runs first
>>>A/2**6
0.0625
#2**6 is 64
>>>4/64
0.0625
Multiplication and division:
 In this scenario Python will run the equation from left to right since
multiplication and division have the precedence
Example:
#multiplication and division
#in this case division is run first then multiplied by 3
>>>5/4*3
3.75
>>>3*4/5
2.4
Multiplication and addition:
 Multiplication will run before an addition equation since multiplication
has more precedence over addition
Example:
#multiplication and addition
>>>2+4*4
18
Addition and subtraction:
 In this scenario the equation will run left to right since addition and
subtraction are on the same level
Example:
>>>2+3-5+8-4+2-9
-3
Example:
X = (15+6)-10*4
Print (X)
 In the expression to evaluate the value of x the brackets have highest of
all precedence
15+6 is 21
10*4 is 40
21-40 is -19
Operator precedence rule in python
Operator Meaning
() Parentheses
** Exponent
+X, -X, ~X Unary plus, unary minus, bitwise
NOT
*, /, //, % Multiplication, division, floor
division, modules.
+, - Addition, subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
NOT Logical NOT
AND Logical AND
OR Logical OR

Associativity of python operators:

 We can see in the above table more than one operator exits in the same
group
 Associativity is the order in which an expression is evaluated that has
multiple operators of the same precedence. Almost all the operators
have left to right associativity

#left-right associativity
#output:3
Print (5*2//3)

You might also like