CHAPTER 2
1MARKS
1.W hat w ill be the output of the follow ing expression if it is executed in Py thon
interactive mode?
16 % 3
Ans. 1
2. W hat w ill be the output of the follow ing program?
X=5
Y=5
print(X/Y)
Ans. 1.0
3. W hat w ill be the output of the follow ing statement?
print(15 + 20 / 5 + 3 * 2 - 1)
Ans. 24 .0
4 . W hat is the maximum length of a Py thon identif ier?
Ans. No f ix ed length is specif ie d by default for a Py thon.
5. Which of the following type of Python operator willonly print True or False in output when
we use it in our program?
Ans. Comparison operator
6. W hat arithmetic operators cannot be used w ith strings in Py thon?
Ans. Minus
7. W hat are the tw o main types of functions in Py thon?
Ans. Built-in function & User defined function
8. W hich of the follow ing is the use of id() function in py thon?
Ans. In Py thon Id function returns the identity of the object
9. W hich of the character is used to give single-line comments in Py thon?
Ans. #
10 . W hich of the follow ing functions is a built-in function in py thon?
Ans. Print()
5 Marks
1.W hat is a literal? Explain the types of literals? W hat are the different modes that
can be used to test Py thon Program ? 1+2+2
Ans. Literal is a raw data given in a variable or constant.
In Py thon, there are various types of literals.
(i) Numeric
(ii) String
(iii) Boolean
The modes that can be used to test Py thon program are
(i) Interactive mode
(ii) Script mode
2. Write short notes on Tokens. W hat are the different operators that can be used
in Py thon ? 3+2
Ans. Py thon breaks each logical line into a sequence of elementary lexical
components know n as Tokens. The normal token types are
(i) Identifiers,
(ii) Keyw ords,
(iii) Operators,
(iv) Delimiters and
(v) Literals.
Ans. The operators that can be used in Py thon
(i) Arithmetic operators
(ii) Relational or Comparative operator
(iii) Logical operators
(iv) Assignment operators
(v) Conditional operator
3. Explain Ternary operator w ith examples. Is Py thon Object- oriented or
Functional Programming? 3+2
Ans. (i) Ternary operator is also know n as conditional operator that evaluate
something based on a condition being true or false.
(ii) It simply allow s 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 4 9 < 50 else 70 // min = 50
min = 50 if 4 9 > 50 else 70 // min = 70
Py thon is considered a multi-paradigm language.
Py thon follow s the object- oriented paradigm
Py thon allow s the creation of objects and their manipulation through specific
methods
It supports most of the features of OOPS such as inheritance and polymorphism
Py thon follow s the functional programming paradigm
Functions may be used as the first- class object
Py thon supports Lambda functions w hich are characteristic of the functional
paradigm
4 . W hat are string literals? Explain. W hat is Escape sequences w ith examples.
4 +1
Ans. (i) In Py thon, a string literal is a sequence of characters surrounded by
quotes. Py thon 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 w ith triple- quote "' "' is used to give multi-line string literal.
To test String Literals:
# Demo Program to test String Literals
strings = "This is Py thon"
char = "C"
multiline_str = "'This is a multiline string w ith more than one line code.'"
print (strings)
print (char)
print (multiline_str)
#End of the Program
Output:
This is Py thon
C
This is a multiline string w ith more than one line code.
(i) ' In Py thon strings, the backslash " \" is a special character, also called
the ’’escape” character.
(ii) It is used in representing certain w hitespace characters: ”\t” is a tab, ” \n” is a
new line, and ” \r” is a carriage return.
(iii) For example to print the message "It's raining", the Py thon 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̀,0 0 ,0 0 0 follow the particulars of Column 1, else follow Column 2. 5+10
Ans. A script is a text file containing the Py thon statements. Py thon Scripts are
reusable code. Once the script is created, it can be executed again and again
w ithout retyping. The Scripts are editable.
Creating Scripts in Py thon:
(i) Choose File →New File or press Ctrl + N in Py thon shell w indow.
A - A script is a text frame
R - Text file contain Py thon script
(1) All text file does not Py thon scripts
(2) All text file must contain Py thon script
(3) A is T B
(ii) An untitled blank script text editor w ill be displayed on screen.
(iii) Type the code in Script editor
Saving py thon 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 w here you w ant to save your
Py thon code, and type the file name in File Name box. Py thon files are by
default saved w ith extension .py . Thus, w hile creating Py thon scripts using
Py thon Script editor, no need to specify the file extension.
(iv) Finally, click Save button to save your Py thon script.
Executing Py thon Script:
(i) Choose Run→Run Module or press F5
To Execute Py thon Script
(ii) If code has any error, it w ill be show n in red color in the IDLE
w indow," and Py thon 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 w ill appear in the IDLE w indow of Py thon.
Sales=float(input(‘Enter Total Sales of the Month:’))
if Sales >= 10 0 0 0 0 :
basic = 4 0 0 0
hra = 20 * basic/10 0
da = 110 * basic/10 0
incentive = Sales * 10 /10 0
bonus = 10 0 0
conveyance = 50 0
else:
basic = 4 0 0 0
hra = 10 * basic/10 0
da = 110 * basic/10 0
incentive = Sales * 4 /10 0
bonus = 50 0
conveyance = 50 0
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:10 0 0 0 0
Salary Receipt of Employee
Total Sales = 10 0 0 0 0 .0
Basic = 4 0 0 0
HRA = 80 0 .0
DA = 4 4 0 0 .0
Incentive = 10 0 0 0 .0
Bonus = 10 0 0
Conveyance = 50 0
Gross Salary = 20 70 0 .0
2. Discuss in detail about Tokens in Py thon. Write a Function Prototype That Takes
a Variable Number of Arguments. W hat Is the Output Of: Print(__name__)? Justify
Your Answ er. Write a program to display the pattern of stars given as follow s:
5+3+2+5
*
* *
* * *
* * * *
* * * * *
Ans. Py thon breaks each logical line into a sequence of elementary lexical
components know n as Tokens. The normal token types are
(i) Identifiers,
(ii) Keyw ords,
(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 w ith an alphabet (A..Z or a..z) or underscore (_).
Identifiers may contain digits (0 .. 9).
Py thon identifiers are case sensitive i.e. uppercase and low ercase letters are
distinct.
Identifiers must not be a py thon keyw ord.
Py thon does not allow punctuation character such as % ,$, @ etc., w ithin
identifiers.
(ii) Keyw ords: Keyw ords are special w ords used by Py thon interpreter to
recognize the structure of program. As these w ords have specific meaning for
interpreter, they cannot be used for any other purpose.
(iii) Operators: In computer programming languages operators are special
symbols w hich 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 w hen used w ith operator
are know n as operands.
(iv) Delimiters: Py thon uses the symbols and symbol combinations as delimiters
in expressions, lists, dictionaries and strings. Follow ing are the delimiters.
(v) Literals : Literal is a raw data given in a variable or constant. In Py thon, there
are various types of literals.
Numeric
String
Boolean.
The function prototype is as follow s:
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 w ith 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 w ith examples. W hat Is the Difference
Betw een Matrices and Arrays? W hat Is the Difference Betw een range() and
xrange() Functions in Py thon? Check if the number entered is prime or not.
5+3+2+5
Ans. Input and Output Functions: A program needs to interact w ith 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 Py thon, input( ) function is used to accept data as input at run time. The
syntax for input() function is,
Variable = input (“ prompt string”)
(ii) W here, prompt string in the syntax is a statement or message to the user, to
know w hat 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 w hatever 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 w ill not know w hat 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 w ill not know w hat is to be typed as input. If the user inputs irrelevant data
as given in the above example, then the output w ill be unexpected. So, to make
your program more interactive, provide prompt string w ith 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 w ill 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 Py thon, the print() function is used to display result on the screen. The
syntax for print() is as follow s :
(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 Py thon Programming”)
Welcome to Py thon 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 w hich is specified w ithin print
(). Comma (,) is used as a separator in print () to print more than one item.
Matrices Arrays
An array is a
A matrix comes from linear algebra and is a sequence of objects
tw o- dimensional representation of data of similar data type
It comes w ith a pow erful set of An array w ithin
mathematical operations that allow you to another array forms a
manipulate the data in interesting w ays matrix
range() xrange()
xrange returns an
range returns a Py thon list object xrange 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 Py thon program to find the square root of a number. Explain
RECURSION. W hat Advantage Does the Numpy Array Have over a Nested List?
W hat 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)
w hile better != approx:
approx = better
better = 0 .5 * (approx + n/approx)
print(approx)
RECURSION.
The process in w hich 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 Tow ers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals,
DFS of Graph, etc.
Py thon 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 w ritten 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, Py thon 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 Py thon, 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