You are on page 1of 37

UNIT II

DATA, EXPRESSIONS, STATEMENTS


PART- A (2 Marks)
1. What are keywords? (Dec / Jan 2019)
 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.
 The keywords used in python are: and, del, from, not, while, is, continue, False , import,
from, break.

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

Without using third variable:


X=12
Y = 20
x , y = y, x  interchanging the variables
print x, y

6. What is meant by interpreter?


 An interpreter is a computer program that executes instructions written in a high level
programming language
 It reads the program line by line and performs the computations alternatively.
 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.

Source Code Interpreter Machine code

7. What are modes python interpreter works?


Python has two basic modes:
1. Script mode or Interpreter mode
2. Interactive mode
Interactive Mode:
 The interactive mode involves running the codes directly on the Python shell which can be
accessed from the terminal of the operating system. 
 In the interactive mode executing the commands from the command line with no script
 User can type the an expression and immediately the expression is executed and the result is
printed
 Example:
>>> a=10, b=20
>>> sum= a+b
>>> print sum
Script Mode:
 The normal mode is the mode where the scripted and finished .py files are run in the Python
interpreter
 The python statements can be stored in a file that is saved as file name with .py extension.
 Python system reads and executes the commands from the file

8. What is meant by identifiers?

 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

9. Name the primitive data type in python.


Five primitive data types in python.
 Numbers
 String
 List
 Tuple
 Dictionary

10. Define function and write its types.


 A function is group of statements that performs a specific task
 Larger programs are divides into number of smaller sub programs are called functions
 Each sub programs specifies one or more actions
 It may or may not take arguments
 Two types
1. Built in function
2. User defined function

11. What are mutable and immutable types in python?

 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.

12. What do you mean by flow of execution?


 Flow of execution specifies the execution order of statement during the program run.
 Execution starts from the first statement of the program top to bottom
 Function definition do not alter the flow of execution
 Statement inside the functions are executed until the function is called
Example:
X=2
Y=3
Print x,y  here first executing the x=2 then y=3 and finally print statement

13. What is a variable?


 A variable is an identifier, which holds a value. It is reserved memory location
 Memory space is allocated at the time of variable creation. Based on the data type the memory
is allocated by interpreter.
 The assignment statements are used to create new variables and assign values to them.
Example: a=10
C=25  here a and c are variables

14. Define dictionary data type.


 Dictionary is a data structure that is one kind of hash table. The values are stored as a pair of
keys and values.
 Each key is separated from it’s value by a colon(:). The dictionary values are separated by a
comma.
 Dictionary keys are numbers or strings enclosed by curly brackets { }
Dictionary name = { key1:value , key 2:value2 ….}
Dep = { a1:cse, a2:IT….}

15. State about logical operators available in python language with example. (Aril / May 2019)

Operator Description Example

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.

Not Logical NOT True if operand is false Not a and b is


false.

16. What is meant literals? Write its types.


 Literals can be defined as a data that is given in a variable or constant.
Python support the following literals
1) String literals
2) Numeric literals
3) Boolean literals
4) Literal Collections such as List, Tuples, Dictionary
5) None Literal

17. Define parameter and argument.


Parameter:
 A name used inside a function to refer to the value passed as an argument
def swap( a, b):
here a and b are parameter

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

18. Distinguish between compiler and interpreter.

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

21. What is a module?


 A python module is a file containing definitions and statements
 The python standard specific library is a collection of built in modules, each providing
specific functionality beyond what is included in the core part of the python
 Example:
def add()
a=90
b=78

22. Define Functions


A function is a named sequence of statements that performs a computation. A function takes
an argument and returns a result. The result is called the return value.
Example
def print_1():
print (“welcome”)

23. Define List.


A List is a sequence of values. The values are characters in a list they can be of any type. The
values in a list are called elements.
Examples
[10,20,30,40] number List
[‘a’,’b’,’c’,’d’]-> Character List
[‘a’,20,5,25.5,[20,30]]-> Nested List
[]-> Empty List
6.What do you mean by mutable list.
The values in the list are changed . So it is called mutable list.
>>> n=[17,35]
>>> n[0]=5
>>>n=[5,35]-> n[0] is changed as 5.

24. What are different Membership Operators in python?


In – Evaluates to true, if it finds a variable in the specified sequence and false otherwise.
Not in- Evaluates to true, if it does not finds a variable in the specified sequence and false
otherwise.

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

Operator Precedence Table


Operator Description
() Parenthesis
** Exponentiation (raise to the power)
Complement, unary plus and minus (method names for the last
~+-
two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'td>
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= , %= , /= , //=, -= , += , *=
Assignment operators
**=
is is not Identity operators
in not in Membership operators
not or and Logical operators

 Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom.

ASSOCIATIVITY OF PYTHON OPERATORS


 When two operators have the same precedence, associativity helps to determine which the
order of operations
 Associativity is the order in which expression is evaluated first. Multiple operators having
same precedence
 All the operators have left-to-right associativity
 For example, multiplication and floor division have the same precedence
 Hence, if both of them are present in an expression, left one is evaluates first
 Operator precedence affects how an expression is evaluated
 Testing Left-right associativity
print(4 * 7 % 3)  * is evaluated first
 Testing left-right associativity
print(2 * (10 % 5))
For example:
 x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +,
so it first multiplies 3*2 and then adds into 7.
>>> 10 * 7 // 3
23
>>> 10 * (7//3)
20
>>> (10 * 7)//3
23
 That is 10 * 7 // 3is equivalent to (10 * 7)//3.
 Exponent operator ** has right-to-left associativity in Python.
>>> 5 ** 2 ** 3
390625
>>> (5** 2) **3
15625
>>> 5 **(2 **3)
390625
 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2)
Non Associative Operators
 Assignment operators and comparison operators do not have associativity in Python
 Separate rules for executing assignment and comparison operator
 For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x
< y and y < z, and is evaluates from left-to-right.
 Furthermore, while chaining x = y = z is perfectly valid,
Example:
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print e
 In this example (a+b) is executed first because () having highest precedence than other
operators. Next * and / having same priority, follow the left associativity
 Multiplication is executed first then division is executed
e = ((a + b) * c) / d # (30 * 15 ) / 5
print e
 In this example inner parenthesis is executed first (a+b) then outer parenthesis is executed
first. Finally division is executed
e = (a + b) * (c / d); # (30) * (15/5)
print e
 Here (a+b) is executed first then (c+d) is executed
e = a + (b * c) / d; # 20 + (150/5)
print e
 In this example (b*c) is executed first next division and finally + is executed
Output:
90
90
90
50
2. Appraise the arithmetic operators in python with example.(12 marks April / May 2019)
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
Arithmetic operators
 Arithmetic operators used to perform mathematical operations like addition, subtraction,
multiplication etc.

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

Subtracts right hand operand from left hand


- Subtraction a – b = -10
operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2


Divides left hand operand by right hand operand
% Modulus b%a=0
and returns remainder

Performs exponential (power) calculation on


** Exponent a**b =10 to the power 20
operators

Floor Division - The division of operands where


the result is the quotient in which the digits after the
decimal point are removed. But if one of the 9//2 = 4 and 9.0//2.0 = 4.0,
//
operands is negative, the result is floored, i.e., -11//3 = -4, -11.0//3 = -4.0
rounded away from zero (towards negative infinity)

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

Precedence of Arithmetic operators:


Operator Precedence

** - 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.

3. What is a numerical literal? Give example.(4 marks Jan -2018)


 Literals can be defined as a data that is given in a variable or constant.
Python support the following literals
1) String literals
2) Numeric literals
3) Boolean literals
4) Literal Collections such as List, Tuples, Dictionary
5) None Literal
Numeric literals:
 A number that is directly assigned to a variable is called Numeric Literal. Numeric Literals are
immutable
int: signed integers
 Numbers can be both positive and negative with no fractional part.eg: 500
Long: (long integers
 Integers of unlimited size followed by lowercase or uppercase L eg 1422L
Float: (Floating point)
 Real numbers with both integer and fractional part eg: -26.2
Complex:
 In the form of a+bj where a forms the real part and b forms the imaginary part of complex
number. eg: 45+54j
Example:
n1= 4564 #integer literal
n2 = 454.54 #float literal
n3 = 45+54j #complex number literal
print(n1)
print(n2)
print(n3)
Output:
4564
454.54
(45+54j)
String literals
 String literals can be formed by enclosing a text in the quotes. Use both single as well as
double quotes for a String.
 Example:
Name = 'John'
fathers_name =" Petter"
print(name)
print(fathers_name)
Output:
John
Petter
Types of Strings:
There are two types of Strings supported in Python:
a).Single line String:
 Strings that are terminated within a single line are known as Single line Strings.
Eg:
>>> text1='hello'
b).Multi line String:
 A piece of text that is spread along multiple lines is known as multiple lines String.
There are two ways to create Multiline Strings:
1). Adding black slash at the end of each line.
Eg: >>> text1='hello\
user'
>>> print text1
Output: 'hellouser'
2).Using triple quotation marks:-
Eg:
>>> str2='''''welcome
to
SSSIT'''
>>> print str2
Output: welcome
to
SSSIT
 Two or more string literals enclosed between quotes and to each other are automatically
concatenated.
var ="py" "thon"
print(var)
var="python " "is " "easy " "programming"
print(var)
Output: python
Python is easy programming
Boolean literals:
 A Boolean literal can have any of the two values: True or False.
Example:
Flag = True
flag1 = False
print(flag1)
print(flag)
Output: False
True
Literal Collections:
Collections such as tuples, lists and Dictionary are used in Python
List:
 List contains items of different data types. Lists are mutable i.e., modifiable
 The values stored in List are separated by commas(,) and enclosed within a square
brackets([]). It can store different type of data in a List
 Value stored in a List can be retrieved using the slice operator([] and [:])
 The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator
Tuple:
 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.
Dictionary:
 The dictionary can be created by using multiple key-value pairs enclosed with the small
brackets () and separated by the colon (:).
 The collections of the key-value pairs are enclosed within the curly braces {}.
 Example:
// create list
numbers=[1,2,3,4,5,6,7]
print(numbers)
//create tuple
alph=('a','b','c')
print(alph)
//create Dictionary
detail={'name':'John','phone':8896163869}
print(detail)
Special literals.
 Python contains one special literal i.e., None.
 None is used to specify to that field that is not created. It is also used for end of lists in
Python.
 Example: var =None
print(var)
Output: None
4. Explain the syntax and structure of user defined functions in python with suitable example.
Also discuss parameter passing in function.(12 marks Jan 2019)
Definition:
 A function is group of statements that performs a specific task
 Larger programs are divides into number of smaller sub programs are called functions
 Each sub programs specifies one or more actions
 It may or may not take arguments
 The function contains the set of programming statements enclosed by {}.
 Two types
1. Built in function
2. User defined function
User defined function:
 The function is defined by the user based on their requirements
 User can modify the function according to their requirements
 Example:
Sum(),swap() get(), display()
Creating a function:
It includes
 Header: Begins with the keyword def and ends with :
 Body: Contains one or more statements. Each intended to the same amount of memory space.
 Use def keyword to define the function. The syntax to define a function in python is
def my_function(parameters):
function-suite
return <expression>
 Function starts with “ : “
 Return (expression) exits a function and also returns the result of a function
 Function name should not be keyword
Function calling:
 A function must be defined before the function calling
 Once the function is defined, call it from another function or the python prompt
 To call the function, use the function name followed by the parentheses.
 Syntax:
Function name(parameter)
Example:
def hello_world():  function definition
print("hello world") - body of the function
hello_world()  function calling
Output:
hello world
Example 2: Find the sum of n numbers
def sum(n):  function definition
i=1
sum=0
while i<n:
sum=sum+i
i=i+1
return sum
n=10
print(n)
result=sum(n)  function calling
print result
Output:
55
Built in functions:
 Predefined functions
 Part of the python packages and libraries
 It is treated as a reserved words
Raw input()
Float()
Int()
Example:
Python abs() Function
The python abs() function is used to return the absolute value of a number.
It takes only one argument.
The argument can be an integer and floating-point number
Python abs() Function Example
# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer))
# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))
Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
Python bin() Function
 The python bin() function is used to return the binary representation of a specified integer.
 A result always starts with the prefix 0b.
Python bin() Function Example
x = 10
y = bin(x)
print (y)
Output:
0b1010
Parameters in function:
Parameter:
 A name used inside a function to refer to the value passed as an argument
def swap( a, b):
here a and b are parameter
Argument:
 A value provided to a function when the function is called.
 The value is assigned to the corresponding parameter in the function
Function with no arguments:
 The empty parenthesis in the function indicate that this function does not take any arguments
 Example: def dis():
Print(‘hai’)
Print(‘hello’)
dis()  no argument is passed
Output:
hai
hello
Function with arguments:
def sum(n):  function definition it receives one argument from the function calling
i=1
sum=0
while i<n:
sum=sum+i
i=i+1
print sum
n=10
print(n)
sum(n)  function calling passing one arguments
Output:
55
Functions with return values:
 Function may return a value to the caller using the key word return
 Example:
Def fact(n):
Fact =1
I=1
If n==1:
return 1
else:
fact = n*fact(n-1)
return fact
n=5
print(fact(5))
output:
120
 In the above example the value of factorial is calculated and then return to print statement by
using function calling statement

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

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda

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.

Declaring Variable and Assigning Values


 It allows us to create variable at required time.
 When we assign any value to the variable that variable is declared automatically.
 The equal (=) operator is used to assign value to a variable.

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

Source Code Interpreter Machine code

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

High level source code Compiler Low machine code

Difference between Compiler and Interpreter:


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
Python has two basic modes:
1. Script mode or Interpreter mode
2. Interactive mode
Interactive Mode:
 The interactive mode involves running the codes directly on the Python shell which can be
accessed from the terminal of the operating system. 
 In the interactive mode executing the commands from the command line with no script
 User can type the an expression and immediately the expression is executed and the result is
printed
 In this it gives immediate feedback for each statement while running previous statement in
active memory
 Python prompt starts from >>> symbol
 To execute the script in UNIX and windows type
 Example: to print the variable A and b
>>> a=10, b=20
>>> sum= a+b
>>> print sum

To print the hello world


Script:
print “ hello world”
 It prints hello world by using the keyword print
In the python 3
Print (‘hello world’)
 Here () indicates that print is a function and single quotes represents the beginning and end of
the text to be displayed
The advantages:
 Useful when script is short and we need immediate results
 Faster, to type a command and then press the enter key to get the results
 Good for beginners who need to understand Python basics
The disadvantages:
 It's very tedious to run long pieces of code.
Script Mode:
 To write a long piece of Python code then choose the script mode
 The normal mode is the mode where the scripted and finished .py files are run in the Python
interpreter
 The python statements can be stored in a file that is saved as file name with .py extension.
 Python system reads and executes the commands from the file
> python <filename>
 To run the Python file from the terminal, just type the python keyword followed by the name
of the file. To run a file named "hello.py"
> python hello.py
The output is Hello World
The advantages:
 It is easy to run large pieces of code
 Editing your script is easier in script mode
 Good for both beginners and experts
The disadvantages:
 Can be tedious when to run only a single or a few lines of code.
 Must create and save a file before executing your code.

Key Differences Between Interactive and Script Mod


Interactive Mode Script Mode
In interactive mode, the result is returned A file must be created and saved before
immediately after pressing the enter key executing the code to get results
This is not possible in interactive mode In script mode provides the direct code
editing

8. Explain detail about the operators in the python language.( 16 marks)


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
Arithmetic operators
 Arithmetic operators used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

Subtracts right hand operand from left hand


- Subtraction a – b = -10
operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

Divides left hand operand by right hand operand


% Modulus b%a=0
and returns remainder

Performs exponential (power) calculation one


** Exponent a**b =10 to the power 20
operators

Floor Division - Floor division - division that


// results into whole number adjusted to the left in the x // y
number line

Unary Arithmetic Operators:

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.

Assume variable a holds 10 and variable b holds 20, then


Operator Description Example
== If the values of two operands are equal, results is true (a == b) is not true.
!= If values of two operands are not equal, results is true (a != b) is true.
If values of two operands are not equal, results is true (a <> b) is true. This is
<>
similar to != operator.
If the value of left operand is greater than the value of
> (a > b) is not true.
right operand, then condition becomes true.
If the value of left operand is less than the value of right
< (a < b) is true.
operand, then condition becomes true.
If the value of left operand is greater than or equal to the
>= (a >= b) is not true.
value of right operand, then condition becomes true.
If the value of left operand is less than or equal to the
<= value of right operand, then condition becomes true. (a <= b) is true.

Example:
x=5
y=7
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)

When you run the program, the output will be:


x >y is False
x <y is True
x == y is False

Python Assignment Operators:


 Assignment operators are used in Python to assign values to variables
 Assume variable a holds 10 and variable b holds 20, then

Operator Description Example


= Assigns values from right side operands to left side c = a + b assigns value of
operand a + b into c
+= Add AND It adds right operand to the left operand and assign c += a is equivalent to c =
the result to left operand c+a
-= Subtract AND It subtracts right operand from the left operand and c -= a is equivalent to c =
assign the result to left operand c-a
*= Multiply AND It multiplies right operand with the left operand and c *= a is equivalent to c =
assign the result to left operand c*a
/= Divide AND It divides left operand with the right operand and c /= a is equivalent to c =
assign the result to left operand c / ac /= a is equivalent to
c=c/a
%= Modulus AND It takes modulus using two operands and assign the c %= a is equivalent to c =
result to left operand c%a
**= Exponent Performs exponential (power) calculation on
AND operators and assign value to the left operand c **= a is equivalent to c
= c ** a

Python Logical Operators:


 Logical operators are the and, or, not operators

Operator Description Example

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.

Not Logical NOT True if operand is false Not a and b


is false.

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)

Operator Description Example

in True if value/variable is found in the sequence x in y, x is a member of sequence y

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.

9. Define function?.What are the different types of arguments in python


A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for application and a high degree of code reusing.
Defining a Function
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −
#!/usr/bin/python
STUDENTSFOCUS.COM
def printme( str ):
"This prints a passed string into this function"
print str
return;
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the
calling function. For example −
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Function Arguments
You can call a function by using the following types of formal arguments:
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
STUDENTSFOCUS.COM
print str
return;
printme()
When the above code is executed, it produces the following result:
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways −
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")
My string
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Name: miki
Age 50
Name: miki
Age 35
STUDENTSFOCUS.COM
Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
Output is:
10
Output is:
70
60
50

10.

You might also like