UNIT II PSPP
UNIT II PSPP
UNIT II PSPP
2. State the reasons to divide the programs into functions? (Dec / Jan 2019)
The length of the source program can be reduced by dividing it into smaller functions
Function makes program easy to understand and maintain
Using the function it is very easy to identify the location of errors and debug an error
The user defined function can be used in many other source programs when it is necessary
Once the function was developed, it can be reused with or without modifications when it’s
need.
Reduce the time and cost of program development
3. Name the four types of scalar objects python has. (Dec / Jan 2018)
Data type is a category of values
Data type of an object define what operation to be performed
Four types of scalar objects are
1. Integers – type int
2. Floating point numbers – type float
3. Strings – type str
4. Booleans – type bool
5. List
4. What is a tuple? How literals of type tuple are written? Give example. (Dec / Jan 2018)
A tuple is an immutable list. Once a tuple has been created, can't add elements to a tuple or
remove elements from the tuple. It is a read only list.
A tuple is defined as a finite, static list of numbers or string. The set of elements is enclosed in
the parentheses. The values can be any data type and they are indexed by integers.
But tuple can be converted into list and list cannot be converted in to tuple.
Literals of type tuples are enclosed within the “( )”
Example:
>>> t=(‘a’, 234, ‘abi’)
5. Write the python program to exchange two variables using function. (Aril / May 2019)
def swap( a,b): function definition statement
temp =a
a=b
b=temp
print a,b it displays the result
x=12
y=34
swap(x,y) function calling statement
Output is 34 12
User defined function name and variable names are called as identifiers.
In python a name given to a variable, function, class, module and other objects
An identifier starts from A to Z, a to z or underscore followed by any number of letters or
digits
Spaces not allowed and it’s not accept the @, % ,& ,$
Python is a case sensitive Ex: Hello and hello are different identifiers
Keyword cannot be identifier
A mutable object can be changed after it is created. A Sate or value can be changed. Objects
of built-in types like list and dictionaries are mutable. User can delete, add and edit any value
inside the string and tuple.
An immutable object can't be changed after it is created. A Sate or value cannot be changed.
Objects of built-in types like int, float, bool, str, tuple. User cannot delete, add and edit any
value inside the string and tuple.
15. State about logical operators available in python language with example. (Aril / May 2019)
and Logical If both the operands are true then condition becomes true. a and b is true.
AND
or Logical OR If any of the two operands are non-zero then condition a or b is true.
becomes true.
Argument:
A value provided to a function when the function is called.
The value is assigned to the corresponding parameter in the function
X=12
Y=3
swap(x,y) here x and y are argument
Compiler Interpreter
Compiler will take whole program and Interpreter translate a program line by line
translates it
Intermediate code is generated It may generate intermediate code and execute it
immediately
Compiler is faster. Used in C, C++, C# Interpreter is execution is slow compared with
compiler. Used in RUBY, Python
Time consumption is high Time consumption is low
When an error occurs it stops its translation and When an error occurs it prevents its translation and
after removing error again the whole program is after removing error resumes the translation
translated
Two steps process, Compiler first source code is One step process in which source code is compiled
executed first and its translated into target code and executed at the same time
then executed
19. Define indentation give one example.
White spaces at the beginning of the line is called indentation
Spaces and tabs at the beginning of the logical line determines the indentation level of that
logical line
Indentation groups statements to form a block of statements
Python very strictly checks the indentation level and gives an error if indentation is not correct
Example : def ad(a,b):
c=a+b
print c
x=10
y =20
20. Write a python program using function to find the sum of first n even numbers and print
the result.(6 marks Jan 2018)
def sum(n): Function Definition Statements
i=o
sum=0
while i<n:
sum=sum+i
i=i+2
return sum -- > it returns the result the function
n=input(‘enter the limit’)
print(n)
result=sum(n) function calling statements
print (“sum =” result )
output:
enter the limit: 10
sum = 30
PART -B
1. Describe about the concept of precedence and associativity of operators with example.( 16
marks April / May 2019, Jan -19, Jan-2018)
Operators:
An operator is a special symbol that performs particular mathematical or logical computations
on operands
Operands:
The values that are applied to the operator are called operands
Operator Precedence:
When an expression contains more than one operator, the order of evaluation depends on the
Precedence of Operations
For example, multiplication and division has higher precedence than addition and subtraction.
>>> 20 – 5*3
5
But Change this order using parentheses () as it has higher precedence
>>> (20 - 5) *3
45
The operator precedence in Python are listed in the following table. It is in descending order,
upper group has higher precedence than the lower ones
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom.
Operands:
The values that are applied to the operator are called operands
Arithmetic operators
Arithmetic operators used to perform mathematical operations like addition, subtraction,
multiplication etc.
Example
x=7
y=3
print('x + y =', x+y)
print('x - y =', x-y)
print('x * y =', x*y)
print('x / y =', x/y)
print('x // y =', x//y)
print('x % y =', x%y)
print('x ** y =', x**y)
Output:
x + y = 10
x-y=4
x * y = 21
x / y = 2.3333333333333335
x // y = 2
x%y=1
x ** y = 343
** - Exponent 1
*, /, % , // 2
+, -, 3
Example 1:
a=10
b=20
c= 5
d = a+b / c *2
In this example first division is executed, next multiplication and finally addition
d= 10+20+/5*2 follow the left associativity
d = 10+4*2
d = 10+8
d = 18
print d
Output is 18
Example2:
>>> 4 /2 **2
>>> 4 / 36
>>> 0.0625
In this example exponent having highest precedence, so it will execute first.
5. Mention the list of keywords in python. Compare it with variable name.( 8 marks April
-2019)
Keyword:
A keyword is a reserved word that is used by the compiler to parse a program. They have
predefined meaning.
Keywords cannot be used as variable names. Python has 33 keywords
Each keyword have a special meaning and a specific operation
True False None and as
VARIABLES
A variable is a name that refers to a value.
Variable reserved memory locations to store values. when you create a variable you reserve
some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory.
Variable Names
Programmers generally choose names for their variables that are meaningful
The Rules
Variables names must start with a letter or an underscore, such as:
_mark
mark_
The remainder of your variable name may consist of letters, numbers and underscores.
subject1
my2ndsubject
un_der_scores
Names are case sensitive.
case_sensitive, CASE_SENSITIVE, and Case_Sensitive are each a different
Variable.
Can be any (reasonable) length
There are some reserved (KeyWords)words which you cannot use as a variable name
The interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names.
Good Variable Name
Choose meaningful name instead of short name. roll_no is better than rn.
Maintain the length of a variable name. Roll_no_of_a_student is too long?
Be consistent; roll_no or RollNo
Begin a variable name with an underscore(_) character for a special case.
Output:
10
ravi
20000.67
Multiple Assignments
Assigning a value to multiple variables in a single statement which is also known as multiple
assignments.
Apply multiple assignments by assigning a single value to multiple variables or assigning
multiple values to multiple variables
1. Assigning single value to multiple variables
Eg:
x=y=z=50
print y
print x z
Output: 50 50 5 0
a,b,c=5,10,15
print a
print b
print c
Output: 5 10 15
6. What are the statements? How are they constructed from variable and expression in python?
( 8 marks April / May 2019).
A statement is an instruction that the Python interpreter can execute.
Example: x=10
Y=20
Print x, y
Two types of statements:
print
Assignment
Print Statement:
The print statements are typed on the command line and Python executes it and displays the
result
The result of a print statement is a value.
Assignment statements don’t produce a result.
A python programs contains a sequence of statements.
If there is more than one statement, the results appear one at a time as the statements execute.
Example:
print 1
x=2
print x
produces the output as
1
2
Assignment statement:
A statement that assigns a value to the variable
To the left of the assignment operator, =, is a name
To the right of the assignment operator is an expression which is evaluated by the Python
interpreter and then assigned to the name.
n=n+1
n plays a very different role on each side of the =. On the right it is a value and makes up part
of the expression which will be evaluated by the Python interpreter before assigning it to the
name on the left
Assignment is defined recursively depending on the form of the list. When a list is part of a
mutable object, the mutable object must ultimately perform the assignment
Assignment of an object to a target list is recursively defined as follows
1. If the target list is a single target: The object is assigned to that target.
2. If the target list is a comma-separated list of targets: The object must be an iterable
with the same number of items as there are targets in the target list, and the items are
assigned, from left to right, to the corresponding targets.
Assignment of an object to a single target is recursively defined as follows.
1. If the target is an identifier (name):
If the name does not occur in a global statement in the current code block: the name is
bound to the object in the current local namespace.
Otherwise: the name is bound to the object in the current global namespace.
2. If the target is a target list enclosed in parentheses or in square brackets:
The object must be an iterable with the same number of items as in the target list, and
its items are assigned, from left to right, to the corresponding targets
3. If the target is an attribute reference:
The primary expression in the reference is evaluated. It should yield an object with
assignable attributes
class Cls:
x=3 # class variable
inst = Cls()
inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
4. If the target is a subscription:
The primary expression in the reference is evaluated. It should produce either a
mutable sequence object or a mapping object Next, the subscript expression is
evaluated.
5. If the target is a slicing:
The primary expression in the reference is evaluated. It should yield a mutable
sequence object
The assigned object should be a sequence object of the same type. Next, the lower and
upper bound expressions are evaluated
The length of the slice may be different from the length of the assigned sequence,
changing the length of the target sequence
Expression statements:
An expression is a combination of values, variables, and operators. Type an expression on the
command line, the interpreter evaluates it and displays the result
Expression statements are used to compute and write a value, or to call a procedure.
Expression statements are allowed and sometimes useful.
The syntax for an expression statement is:
expression_stmt ::= expression_list
An expression statement evaluates the expression list which may be a single expression
In interactive mode, if the value is not None, it is converted to a string using the built-in repr()
function and the resulting string is written to standard output on a line by itself
>>> 1 + 1
2
The evaluation of an expression produces a value and expressions can appear on the right
hand side of assignment statements.
>>> 17
17
the print statement prints the value of the expression
>>> message = "What's up, Doc?"
>>> message
"What's up, Doc?"
>>> print message
What's up, Doc?
In a script, an expression all by itself is a legal statement, but it doesn’t do anything.
The script produces no output at all.
17
3.2
"Hello, World!"
1+1
7. Sketch the structures of interpreter and compiler. Detail the difference between them.
Explain how python works in interactive mode and script mode with example. (8 marks April /
May 2019).
Interpreter:
An interpreter is a computer program that executes instructions written in a high level
programming language and produce the result as intermediate code
I reads the program line by line or statement by statement and performs computations
It can execute the source code directly or translate the source code in to machine code.
It processes the program a minimum one at a time
No need compilation and linking process
Compiler:
A compiler is a software program that transforms source code that is written in a high-level
programming language into a low level object code (binary code) in machine language
The process of converting high-level programming into machine language is known as
compilation.
The processor executes object code
Once the program is compiled, then the program can be executed repeatedly without any
changes
Operator Description
+ Returns numeric argument without any change
- Returns numeric argument with it’s sign changed
Python Comparison Operators
These operators compare the values on left side with right side them. They are also called
Relational operators.
Example:
x=5
y=7
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
and Logical If both the operands are true then condition becomes true. a and b is
AND true.
or Logical OR If any of the two operands are non-zero then condition becomes a or b is
true. true.
Example:
x = True
y = False
printx and y)
print(x or y)
print(not x)
Output: When you run the program, the output will be:
False
True
False
Membership Operators
in and not in are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence (string, list, tuple, set
and dictionary)
not in True if value/variable is not found in the sequence x not in y, here x is not a member of
sequence y
x = 'Python Programming'
print('Program' not in x)
print('Program' in x)
print('program' in x)
Output: When you run the program, the output will be:
False
True
False
Identity operators:
It is used to check whether two values are located on the same part of the memory or not
Identity operators are is and is not are the identity operators in python
Operators Description
is It returns true if both the operands are point
to the same object
is not It returns false if both the operands are point
to the same object
Example:
A=10
Y=10
Print(x is y )
Print (x is not y)
Output:
True
False
Bitwise operators:
Operators Description Example
Both the operands are true then it (a & b) (means 0000 1100)
& Binary AND
set bit as 1
If anyone operand is true the it set (a | b) = 61 (means 0011 1101)
| Binary OR
bit as 1
^ Binary XOR If any one (a ^ b) = 49 (means 0011 0001)
It is unary and has the effect of (~a ) = -61 (means 1100 0011 in
~ Binary Ones Complement 'flipping' bits. 2's complement form due to a
signed binary number.
The left operands value is moved a << 2 = 240 (means 1111 0000)
<< Binary Left Shift left by the number of bits specified
by the right operand.
The left operands value is moved a >> 2 = 15 (means 0000 1111)
>> Binary Right Shift right by the number of bits
specified by the right operand.
10.