CHAPTER 2
1MARKS
[Link] will be the output of the following expression if it is executed in Python interactive
mode?
16 % 3
Ans. 1
2. What will be the output of the following program?
X=5
Y=5
print(X/Y)
Ans. 1.0
3. What will be the output of the following statement?
print(15 + 20 / 5 + 3 * 2 - 1)
Ans. 24.0
4. What is the maximum length of a Python identifier?
Ans. No fixed length is specified by default for a Python.
5. Which of the following type of Python operator will only print True or False in output when we use it in
our program?
Ans. Comparison operator
6. What arithmetic operators cannot be used with strings in Python?
Ans. Minus
7. What are the two main types of functions in Python?
Ans. Built-in function & User defined function
8. Which of the following is the use of id() function in python?
Ans. In Python Id function returns the identity of the object
9. Which of the character is used to give single-line comments in Python?
Ans. #
10. Which of the following functions is a built-in function in python?
Ans. Print()
5 Marks
[Link] is a literal? Explain the types of literals? What are the different modes that can be
used to test Python Program ? 1+2+2
Ans. Literal is a raw data given in a variable or constant.
In Python, there are various types of literals.
(i) Numeric
(ii) String
(iii) Boolean
The modes that can be used to test Python program are
(i) Interactive mode
(ii) Script mode
2. Write short notes on Tokens. What are the different operators that can be used in Python ?
3+2
Ans. Python breaks each logical line into a sequence of elementary lexical components
known as Tokens. The normal token types are
(i) Identifiers,
(ii) Keywords,
(iii) Operators,
(iv) Delimiters and
(v) Literals.
Ans. The operators that can be used in Python
(i) Arithmetic operators
(ii) Relational or Comparative operator
(iii) Logical operators
(iv) Assignment operators
(v) Conditional operator
3. Explain Ternary operator with examples. Is Python Object-oriented or Functional
Programming? 3+2
Ans. (i) Ternary operator is also known as conditional operator that evaluate something based
on a condition being true or false.
(ii) It simply allows testing a condition in a single line replacing the multiline if-else making
the code compact.
Variable Name = [on_true] if [Test expression] else [on_false]
(iii) Example:
min = 50 if 49 < 50 else 70 // min = 50
min = 50 if 49 > 50 else 70 // min = 70
Python is considered a multi-paradigm language.
Python follows the object-oriented paradigm
Python allows the creation of objects and their manipulation through specific methods
It supports most of the features of OOPS such as inheritance and polymorphism
Python follows the functional programming paradigm
Functions may be used as the first-class object
Python supports Lambda functions which are characteristic of the functional paradigm
4. What are string literals? Explain. What is Escape sequences with examples.
4+1
Ans. (i) In Python, a string literal is a sequence of characters surrounded by quotes. Python
supports single, double and triple quotes for a string.
(ii) A character literal is a single character surrounded by single„or double quotes. The value
with triple-quote "' "' is used to give multi-line string literal.
To test String Literals:
# Demo Program to test String Literals
strings = "This is Python"
char = "C"
multiline_str = "'This is a multiline string with more than one line code.'"
print (strings)
print (char)
print (multiline_str)
#End of the Program
Output:
This is Python
C
This is a multiline string with more than one line code.
(i) ' In Python strings, the backslash "\" is a special character, also called
the ’’escape” character.
(ii) It is used in representing certain whitespace characters: ”\t” is a tab, ”\n” is a newline,
and ”\r” is a carriage return.
(iii) For example to print the message "It's raining", the Python command is
>>> print ("It\'s raining")
It's raining
15 Marks
Describe in detail the procedure Script mode programming.
Write a program to calculate the salary of a medical representative considering the sales
bonus and incentives offered to him are based on the total sales. If the sales exceed or equal
to
`1,00,000 follow the particulars of Column 1, else follow Column 2. 5+10
Ans. A script is a text file containing the Python statements. Python Scripts are reusable code.
Once the script is created, it can be executed again and again without retyping. The Scripts
are editable.
Creating Scripts in Python:
(i) Choose File → New File or press Ctrl + N in Python shell window.
A - A script is a text frame
R - Text file contain Python script
(1) All text file does not Python scripts
(2) All text file must contain Python script
(3) A is T B
(ii) An untitled blank script text editor will be displayed on screen.
(iii) Type the code in Script editor
Saving python script:
(i) Choose File → Save or press Ctrl+S
(ii) Now, Save As dialog box appears on the screen.
(iii) In the Save As dialog box, select the location where you want to save your Python
code, and type the file name in File Name box. Python files are by default saved with
extension .py. Thus, while creating Python scripts using Python Script editor, no need to
specify the file extension.
(iv) Finally, click Save button to save your Python script.
Executing Python Script:
(i) Choose Run→Run Module or press F5
To Execute Python Script
(ii) If code has any error, it will be shown in red color in the IDLE window," and
Python describes the type of error occurred. To correct the errors, go back to
Script editor, make corrections, save the file using Ctrl + S or File → Save and
execute it again.
(ii) For all error free code, the output will appear in the IDLE window of Python.
Sales=float(input(‘Enter Total Sales of the Month:’))
if Sales >= 100000:
basic = 4000
hra = 20 * basic/100
da = 110 * basic/100
incentive = Sales * 10/100
bonus = 1000
conveyance = 500
else:
basic = 4000
hra = 10 * basic/100
da = 110 * basic/100
incentive = Sales * 4/100
bonus = 500
conveyance = 500
salary= basic+hra+da+incentive+bonus+conveyance
print(‘Salary Receipt of Employee ‘)
print(‘ Total Sales = ‘,Sales)
print(‘ Basic = ‘,basic)
print(‘ HRA = ‘,hra)
print(‘ DA = ‘,da)
print(‘ Incentive = ‘,incentive)
print(‘ Bonus = ‘,bonus)
print(‘ Conveyance = ‘,conveyance)
print(‘ Gross Salary = ‘,salary)
Output
Enter Total Sales of the Month:100000
Salary Receipt of Employee
Total Sales = 100000.0
Basic = 4000
HRA = 800.0
DA = 4400.0
Incentive = 10000.0
Bonus = 1000
Conveyance = 500
Gross Salary = 20700.0
2. Discuss in detail about Tokens in Python. Write a Function Prototype That Takes a
Variable Number of Arguments. What Is the Output Of: Print(__name__)? Justify Your
Answer. Write a program to display the pattern of stars given as follows: 5+3+2+5
*
**
***
****
*****
Ans. Python breaks each logical line into a sequence of elementary lexical components
known as Tokens. The normal token types are
(i) Identifiers,
(ii) Keywords,
(iii) Operators,
(iv) Delimiters and
(v) Literals.
(i) Identifiers :
■ An Identifier is a name used to identify a variable, function, class, module or object.
■ An identifier must start with an alphabet (A..Z or a..z) or underscore (_).
■ Identifiers may contain digits (0 .. 9).
■ Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
■ Identifiers must not be a python keyword.
■ Python does not allow punctuation character such as %,$, @ etc., within identifiers.
(ii) Keywords: Keywords are special words used by Python interpreter to recognize the
structure of program. As these words have specific meaning for interpreter, they cannot be
used for any other purpose.
(iii) Operators: In computer programming languages operators are special symbols which
represent computations, conditional matching etc. The value of an operator used is
called operands. Operators are categorized as Arithmetic, Relational, Logical, Assignment
etc. Value and variables when used with operator are known as operands.
(iv) Delimiters: Python uses the symbols and symbol combinations as delimiters in
expressions, lists, dictionaries and strings. Following are the delimiters.
(v) Literals : Literal is a raw data given in a variable or constant. In Python, there are various
types of literals.
■ Numeric
■ String
■ Boolean.
The function prototype is as follows:
def function_name(*list)
>>def fun(*var):
>> for i in var:
print(i)
>>fun(1)
>>fun(1,25,6)
In the above code, * indicates that there are multiple arguments of a variable.
__name__ is a special variable that holds the name of the current module. Program execution
starts from main or code with 0 indentations. Thus, __name__ has a value __main__ in the
above case. If the file is imported from another module, __name__ holds the name of this
module.
print(“ Star Pattern Display”)
num=1
x=num
for i in range(1,6,1):
num=num+1;
for j in range(1,num,1):
print(“ * “,end=” “)
x=num+1
print()
print(“End of Program”)
Output
Star Pattern Display
*
**
***
****
*****
End of Program
3. Explain input() and print() functions with examples. What Is the Difference Between
Matrices and Arrays? What Is the Difference Between range() and xrange() Functions in
Python? Check if the number entered is prime or not. 5+3+2+5
Ans. Input and Output Functions: A program needs to interact with the user to accomplish the
desired task; this can be achieved using Input- Output functions. The input() function helps to
enter data at run time by the user and the output function print() is used to display the result
of the program on the screen after execution.
The input() function :
(i) In Python, input( ) function is used to accept data as input at run time. The syntax for
input() function is,
Variable = input (“prompt string”)
(ii) Where, prompt string in the syntax is a statement or message to the user, to know what
input can be given.
(ii) If a prompt string is used, it is displayed on the monitor; the user can provide expected
data from the input device. The input( ) takes whatever is typed from the keyboard and stores
the entered data in the given variable.
(iv) If prompt string is not given in input() no message is displayed on the screen, thus, the
user will not know what is to be typed as input.
(v) Example 1 : input() with prompt string
>>> city=input (“Enter Your City:”)
Enter Your City: Madurai
>>> print (“I am from “, city)
I am from Madurai
(v) Example 2 : input() without prompt string
>>> city=input
Madurai
>>> print (“I am from “, city)
I am from Madurai
(vii) Note that in example-2, the input( ) is not having any prompt string, thus the user will
not know what is to be typed as input. If the user inputs irrelevant data as given in the above
example, then the output will be unexpected. So, to make your program more interactive,
provide prompt string with input().
(viii)The input ( ) accepts all data as string or characters but not as numbers. If a numerical
value is entered, the input values should be explicitly converted into numeric data type. The
int( ) function is used to convert string data as integer data explicitly. We will learn about
more such functions in later chapters.
(ix) Example 3 :
x = int (input(“Enter Number 1: ”))
y = int (input(“Enter Number 2: ”))
print (“The sum = ”, x+y)
(x) Output:
Enter Number 1: 34
Enter Number 2: 56
The sum = 90
(xi) Example 4: Alternate method for the above program
x,y=int (input("Enter Number 1 :")),
int(input("Enter Number 2:"))
print ("X = ",x," Y = ",y)
(xii) Output:
Enter Number 1:30
Enter Number 2:50
X = 30 Y = 50
The print() function :
(i) In Python, the print() function is used to display result on the screen. The syntax for print()
is as follows :
(ii) Example :
print (“string to be displayed as output ” )
print (variable)
print (“String to be displayed as output ”, variable)
print (“Stringl ”, variable, “String 2”, variable, “String 3” ......)
(iii) Example :
>>> print (“Welcome to Python Programming”)
Welcome to Python Programming
>>>x = 5
>>>y = 6
>> >z = x + y
>>> print (z)
11
>>> print (“The sum = ”, z)
The sum =11
>>> print (“The sum of”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11
(iv) The print () evaluates the expression before printing it on the monitor.
(v) The print () displays an entire statement which is specified within print (). Comma (,) is
used as a separator in print () to print more than one item.
Matrices Arrays
A matrix comes from linear algebra and is a two- An array is a sequence of
dimensional representation of data objects of similar data
type
It comes with a powerful set of mathematical
operations that allow you to manipulate the data in An array within another
interesting ways array forms a matrix
range() xrange()
xrange returns an xrange
range returns a Python list object
object
num=int(input(“Enter the Number:”))
x=num
for i in range(2,num):
if num%i==0: #Check if entered number is divisible by i
flag=0
break
else:
flag=1
if(flag==1):
print(num,” is Prime “)
else:
print(num,” is not prime “)
Output
#Test case 1:
Enter the Number:23
23 is Prime
#Test case 2:
Enter the Number:12
12 is not prime
4. Write a Python program to find the square root of a number. Explain RECURSION. What
Advantage Does the Numpy Array Have over a Nested List? What Does the // Operator Do?
5+5+3+2
n=int(input("Enter a number to find Square Root:"))
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
print(approx)
RECURSION.
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH),
Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
Python program:
# take input from the user
num = int(input("Enter a number: "))
def fact(n):
if n == 1:
return n
else:
return n*fact(n-1)
print(“Factorial of n numbers is :%d” %(fact(n)))
Numpy is written in C so that all its complexities are backed into a simple to use a module.
Lists, on the other hand, are dynamically typed. Therefore, Python must check the data type
of each element every time it uses it. This makes Numpy arrays much faster than lists.
Numpy has a lot of additional functionality that list doesn’t offer; for instance, a lot of things
can be automated in Numpy.
In Python, the / operator performs division and returns the quotient in the float.
For example: 5 / 2 returns 2.5
The // operator, on the other hand, returns the quotient in integer.
For example: 5 // 2 returns 2