0% found this document useful (0 votes)
262 views

Algorithmic Problem Solving 1

The document discusses different types of computer languages and translators like interpreters and compilers. It provides details about Python being an interpreted language and how interpreters work by taking source code as input and producing output. Script mode and interactive mode of executing Python programs are also summarized. The document further describes various features, versions, data types like numbers, sequences, sets and mappings supported in Python.

Uploaded by

jarlin jeincy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
262 views

Algorithmic Problem Solving 1

The document discusses different types of computer languages and translators like interpreters and compilers. It provides details about Python being an interpreted language and how interpreters work by taking source code as input and producing output. Script mode and interactive mode of executing Python programs are also summarized. The document further describes various features, versions, data types like numbers, sequences, sets and mappings supported in Python.

Uploaded by

jarlin jeincy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 100

Algorithmic Problem Solving 1.

1
2.2 Problem Solving and Python Programming

UNIT -2

DATA, EXPRESSIONS,
STATEMENTS

2.1. INTRODUCTION OF PYTHON

Types of Computer Languages:


1. Low Level Language :
It is also called as Machine Language. It uses 0’s 1’s to create instructions.
2. Middle Level Language:
It is also called as Assembly Language. It uses mnemonics to create
instructions.
3. High Level Language:
Similar to human language. Example: C,C++,Java
Translator is a computer program to converts a high level program to low level. Compiler and
Interpreter are the translators.

Interpreter
Python is an interpreted language because they are executed by an interpreter. Interpreter
take high level program as input and executes what the program says. It processes the program a
minimum at a time. It read lines and performs computations alternatively. The figure 2.1 explains
the structure of an interpreter.

Source Code Interpreter Output

Fig. 2.1 Function of Interpreter

Compiler
A compiler reads the program and translates it completely to machine readable form called
object code or executable code before the program starts running. Once a program is compiled, the
programcanbeexecutedrepeatedlywithoutfurthertranslations.Thefigure2.2showsthestructure of a
compiler.

Source Compiler Object Execution Output


Code

Fig. 2.2 Function of Compiler


To execute the program code, the interpreter can be used.
There are two different modes to use the interpreter.
1.Interactivemode,
2.Scriptmode.
Data, Expressions, Statements 2.3

Interactive mode:
It is command line shell which gives immediate feedback for each statement, while running
previously fed statements in active memory.
In interactive mode, the program statements can be typed in prompt, so the interpreter
displays the result.

>>>1+1
2
Theprompt>>>(chevron)indicatesthattheinterpreterisready.Interactivemodeexecution is
convenient for smaller programs.

Script mode:
The programcanbestoredinafileandi t u s e s theinterpretertoexecute the file. The python
scripts filename ends with .pyextension.

To execute the script, in UNIX and windows type,


• pythonfilename.py # To execute thefile
For larger programs, the program code can be stored as a script and execute it in the future.

Example:
# first simple program

# To print Hello, World!

print ‘Hello, World!’

It prints Hello, World. In python printing statement uses the keyword print as in the above
mentioned format.

In Python 3, the syntax for printing is slightly different like this, print

(‘Hello, World!’)

The parenthesis indicates that the print is a function. The single quotation represents the
beginning and end of the text to be displayed.

About Python:
 Python was developed buy Guido van Rossum in 1991, a computer programmer at
CWI(Centrum Wiskunde and Informatica))
 It is an object oriented interpreted and high level scripting language.
 It has been used by the companies in real revenue generating products such as Googlesearch
engine, you tube, Bit torrent, for developing commercial robot.
 It is open source and supports cross platform development.

The different versions of python are


 Python 1.0 January 1994
 Python 2.0 April 2001
 Python 3.0 December 2008
 Python 3.6 December 2016
2.4 Problem Solving and Python Programming

 Python 3.8 October 2019

Features of Python:

1. Simple and easy to learn


2. Free and opens source software
3. High level Language
4. Portable
5. Interpreted and interactive
6. Object oriented

Python keywords:
Keywords are reserved words that cannot be used as identifiers. We cannot use a
keyword as variable name, function name or any other identifier. Keywords are case
sensitive. All the keywords except True, False and None are in lowercase. There are 33
and del from not while
As elif global or with
assert else if pass yield
break except import print True
class exec in raise False
continue finally is return None
def for lambda try
keywords.

Python Identifier:
Identifier are names for entities in program such as class, variable and function etc.

Rules for Identifier:


Identifier can contain both letters and numbers. But do not start with a number. The
underscore character (_ ) can be used in variable names . In addition to variables, python has 33
keywords.

Valid identifier:
_sum,test12
Invalid identifier :
$include,if,10python

Values and Types


A value is a basic thing that a program works with, like a letter or a number. Ex: 1,2 and
‘Hello, World!’.

The values belong to different data types. In Python, the standard data types available are:
Data, Expressions, Statements 2.5
(1) Numbers : Integer, Boolean, Floating point, complex
(2) Sequences: String, List, Tuple
(3) Sets
(4) Mappings: Dictionary
(5) None

2.1.1.1 Number data type


Number data type stores numerical values. It supports four numerical types.
(1) int (signed numbers like 10, -20)
• Integers are the whole numbers with no fractional parts.
• It may be positive, negative, or zero
• It can have unlimited size in python3
(2) long (long integers represented in octal & hexadecimal like, ox3245 and 234L)
• Python displays long integers with an uppercase L.
(3) float (Floating point real values like3.45)
• Numbers with fractions or decimal point are called floating point numbers.
•It consist of sign(+,-) sequence of decimal digits.
• “e” to indicate the 10th power It is used to express very large or small result.
(4) complex(Complexnumberslike,7.32e-3j).
• A complex number consist of an ordered pair of real floating numbers denoted
by real +imgj (j refers to the square root of -1)
(5) Boolean
•Boolean often called bools, are either TRUE or FALSE condition. These two values
are used when evaluating comparisons and conditional expressions
Sequence
A sequence is an ordered collection of items, indexed by positive integers. It is a comb
ination of mutable and non mutable data types. Three types of sequence data type available are
strings, list and tuple.

2.1.1.2 String data type


String are the sequence of characters represented within quotation marks. It allows either pairs
of single or double quotes. The substring access is possible through the slicing operator ([] or
[:]).Thestringindex0representsbeginningofthestringwhereas,index-1representsendingofthe string.
The following examples illustrate the string and substringaccesses.
Example:
#str – string variable (explained later in this chapter) assigned with a value

str= ‘Hello, World!’

Code Comment Result


print str # prints complete string Hello, World!
print str[0] # prints first character of the string H
2.6 Problem Solving and Python Programming

print str[-1] #prints last character of the string !


print str[1:5] # prints character starting from index 1 to 4 Ello
# prints str[start_at : end_at-1]
print str[2:] #prints string starting at index 2 till end of the string llo, World!
print str * 2 # asterisk (*) -is the repetition operator. Prints the Hello, World!
string two times. Hello,World!
print str + “Hai” # prints concatenated string Hello, World! Hai

2.1.1.3 List data type


Listsarethemostsignificantcompounddatatypescontainelementsofvarioustypes.AList
canholditemsofdifferentdatatypes.Thelistisenclosedbysquarebrackets[]wheretheitemsare separated
by commas. Like string data type, the list values can be accessed using the slice operator ([] or
[:]). The index 0 represents beginning of the list whereas, index -1 represents ending of the list.
The following example illustrates listaccesses.

Example:
list1=[‘abcd’, 345, 3.2,’python’, 3.14]

list2=[234, ‘xyz’]

Code Comment Result


print list1 # prints complete list [‘abcd’, 345, 3.2,’python’,
3.14]
print list1[0] # prints first element of the list Abcd
print list1[-1] #prints last element of the list 3.14
print list1[1:3] # prints elements starting from index 1 to 2 [345, 3.2]
# prints list1[start_at : end_at-1]
print list1[2:] #prints list starting at index 2 till end of the [3.2, ‘python’, 3.14]
list
print list 2 * 2 # asterisk (*) -is the repetition operator. Prints [‘abcd’, 345, 3.2, ‘python’,
the list two times. 3.14, 234, ‘xyz’]
print list1 + list2 # prints concatenated lists [‘abcd’, 345, 3.2,’python’,
3.14, 234, ‘xyz’]

2.1.1.4 Tuple datatype


Tuple is another sequence data type similar to list. A tuple consists of a number of values
separated by commas and enclosed within parentheses. Unlike list, the tuple values cannot be
updated. They are treated as read-only lists. The following example explains the tuple element
access.

Example:
tuple1= (‘abcd’, 345 , 3.2,’python’, 3.14)

tuple2= (234, ‘xyz’)

Code Comment Result


Data, Expressions, Statements 2.7

print tuple1 # prints complete tuple1 (‘abcd’, 345, 3.2, ’python’,


3.14)
print tuple1[0] # prints first element of the tuple1 Abcd
print tuple1[-1] #prints last element of the tuple1 3.14

print tuple1[1:3] # prints elements starting from index 1 to 2 (345, 3.2)


# prints tuple1[start_at : end_at-1]

print tuple1[2:] #prints tuple1 starting at index 2 till the (3.2, ‘python’, 3.14)
end
print tuple 2 * 2 # asterisk (*) -is the repetition operator. (234, 'xyz', 234, 'xyz')
Prints the tuple2 two times.
print tuple1 + # prints concatenated tuples (‘abcd’, 345, 3.2,’python’,
tuple2 3.14, 234, ‘xyz’)

2.1.1.5 Dictionary data type


Dictionary data type is a kind of hash table. It contains key-value pairs. A dictionary key
can be almost any python type, usually numbers or strings. Values can be arbitrary python object.
Dictionaries are enclosed by curly braces {} and values can be assigned and accessed using square
brackets []. The following example explains the dictionary element access.

dict1= {‘name’: ‘ABCD’ , ‘code’ : 6734 , ‘dept’ : ‘Engg’}


dict2= {}
dict2 [‘rollno’] = “II-ITA24”
Code Comment Result
print dict1 # prints complete dictionary { ‘dept’: ‘Engg’, ‘code’:6734,
‘name’ : ‘ABCD’}
print dict1.keys() # prints all keys of dictionary { ‘dept’, ‘code’, ‘name’}

print dict1.values #prints all values of dictionary {‘Engg’, 6734, ‘ABCD’}


print dict2[‘rollno’] # print the value for the key rollno II-ITA24

2.1.1.6 None
2.1.1.7 Sets
A set is an ordered collection of items. Every element is unique and cannot be changed.
A set is created by placing all the items inside curly braces{}, separated by comma. Add() and
update() are used to add new entries or updating existing elements.
Example :
Myset ={2,5}
print(myset)
myset.add(6)
print(myset)
output:
2.8 Problem Solving and Python Programming

{2,5}
{2,5,6}

2.2 Variable
Variable is an identifier that refers to a value. Values mays be numbers and text.No
Declaration is necessary. Declaration happened automatically when the value is assigned.
While creating a variable, memory space is reserved in memory. Based on the data type of
a variable, the interpreter allocates memory. The assignment statements are used to create new
variables and assign values to them.
>>>msg= ‘ Hello, World!’ #string assignemnet
>>> n=12 # integer assignment
>>> pi=3.14
The first statement creates a variable, msg and assigns ‘Hello, World!’ to it. The second
statement creates the variable, n assigns 12 to it. The third statement creates the variable, pi and
assigns the value 3.14.

Variable names can contain both letters and numbers. But do not start with a number. The
underscore character (_ ) can be used in variable names . In addition to variables, python has 31
keywords.
Multiple objects can be assigned to multiple variables as
a,b,c=1,2,3

Python allows assigning a single value to several variables.


Mark1=mark2=mark3=100

Python Input Statement :

Input comes from keyboard. Python has two key functions to deal with end user input. They are
1.input()
2.raw_input()

input()- If user enter integer input, integer will be return.


If user enter string input, string will be returned.

Syntax: variable_name=input(“Expression or statement”)


Example : rollno=input(“Enter rollno”)

raw_input()-if user enters integer or string , string will be returned.

Syntax: variable_name=raw_input(“Expression or statement”)


Example : name=input(“Enter name”)
Data, Expressions, Statements 2.9
Python output Statement :
It is used to output data to the output device(screen). It converts the expressions that are passed,
into a string and displays the result to standard output.
Syntax:
print(“<expression>”,variablename)
name=input(“Enter name”)
print(“Name:”,name)
Output:
Enter name Python
Name:Python
2.3 EXPRESSIONS ANDSTATEMENTS
An expression is a combination of values, variables and operators. A value and a variable,
itself considered as an expression.

Example:
17 #expression
X #expression
X+17 #expression

Astatementisacodethatendswithanewline.Sofar,wehaveseentwokidsofstatements: print and


assignment. Python allows the use of line continuation character (\) to denote that the line
shouldcontinue.

Example:
Total= mark1+ \
mark2+ \
mark3
Butthestatementscontainedwithin[],{}or()bracketsdonotneedtouselinecontinuation characters.
Forexample,

Item= [‘item1’, item2’, ‘item3’, ‘item4’, ‘item5’]

2.4 COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.
Single line comment - #
Multiline comment – ‘’’ ( triple single quotes at the start and end )

Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=5 # creates the variable v and assign the value 5; comment

‘’’ Author : xxxx

Date : 4.5.2020’’’
2.10 Problem Solving and Python Programming

2.5 OPERATORS
An operator is a special symbol that asks the compiler to perform particular mathematical
orlogicalcomputationslikeaddition,multiplication,comparisonandsoon.Thevaluestheoperator is
applied to are called operands.
If operators take one operand are called unary operators. Operators that takes two operand
are called binary operator.
For eg, in the expression 4 + 5, 4 and 5 are operands and + is an operator.

The following tokens are operators in python:


+ – * ** / // %
<< >> & | ^ ~
< > <= >= == != <>

2.5.1 Consider the expression z=x+y


Here x,y and z are the operands. +, = are the operators.

2.5.2 Types ofOperator


Python language supports the following types of operators.
• ArithmeticOperators
• Comparison (Relational)Operators
• AssignmentOperators
• LogicalOperators
• BitwiseOperators
• MembershipOperators
• IdentityOperators
• Unary arithmeticOperators

2.5.1.1 Arithmetic Operators


Operator Description
+ Addition Adds two operands.
- Subtraction Subtracts second operand from first operand.
* Multiplication Multiplies two operands.
/ Division Divides first operand by second operand.
% Modulus Divides first operand by second operand and returns the remainder
** Exponent Performs exponential (power) calculation
// Floor Division Division of operands in which the quotient without fraction is returned
(Integer Division) as a result. If one of the operand is –ve, the result is floored

SampleCode:
a = 21
b = 10
c=0
Data, Expressions, Statements 2.1

c=a+b
print “Result of addition “, c
c=a-b
print “Result of subtraction “, c
c=a*b
print “Result of multiplication “, c
c=a/b
print “Result of division “, c
c=a%b
print “Result of modulus “, c
a=2
b=3
c = a**b
print “Result of exponentiation “, c
a = 10
b=5
c = a//b
print “Result of floor division “, c

Sample Output:
Result of addition 31
Result of subtraction 11
Result of multiplication 210
Result of division 2
Result of modulus 1
Result of exponentiation 8
Result of floor division 2
2.5.1.2 Comparison (Relational) Operators
These operators compare the values of their two operands and determine the relationship
among them.
Operator Description
== If the values of two operands are equal, then this operator returns true.
!= If values of two operands are not equal, then this operator returns true.
2.12 Problem Solving and Python Programming

Operator Description
> If the value of first operand is strictly greater than the value of second operand, then
this operator returns true.
< If the value of first operand is strictly smaller than the value of second operand, then
this operator returns true.
>= If the value of first operand is greater than or equal to the value of second operand,
then this operator returns true.
<= If the value of first operand is smaller than or equal to the value of second operand,
then this operator returns true.

Sample Code and Output:


>>>4 == 4
True
>>>4 != 4
False
>>>4 < 5
True
>>>4 >= 3
True
>>>”A” < “B”
True
>>>

2.5.1.3 Assignment Operators


Operator Description
= Assigns values from right side operand to left side operand.
+= Performs addition using two operands and assigns the result to left side
operand.
-= Subtracts right side operand from the left side operand and assigns the
result to left side operand.
*= Performs multiplication using two operands and assigns the result to left
side operand.
/= Divides left side operand by the right side operand and assigns the result to
left side operand.
%= Findsmodulususingtwooperandsandassignstheresulttoleftsideoperand.
**= Performs exponential calculation and assigns the result to the left side
operand.
//= Performs floor division and assigns the result to the left side operand
Data, Expressions, Statements 2.1

SampleCode:
a = 10
b=5
c=a
print “c is “,c
c = a + b
print “c is “, c
c += a #c=c+a
print “c is “, c
c -=a #c=c-a
print “c is “, c
c *= a #c=c*a
print “c is “, c
c /= a #c=c/a
print “c is “, c
c=2
c %= a #c=c%a
print “c is “, c
c **= a # c = c ** a
print “c is “, c
c //= a # c = c // a
print “c is “, c

Sample Output:
c is 10
c is 15
c is 25
c is 15
c is 150
c is 15
c is 2
c is 1024
c is 102
Data, Expressions, Statements 2.11

2.5.1.4 Logical Operators


Following table shows all the logical operators supported by python:
Operator Description
and Logical AND returns true, if and only if both operands are true.
or Logical OR returns true, if any of the two operands is true.
not Logical NOT returns the logical negation of its operand.
Here, any nonzero number is interpreted as true and zero is interpreted as false. Both the
and operator and the or operator expect two operands. not operator operates on a single operand.

The behaviour of each logical operator is specified in a truth table for that operator.

The truth tables for and, or, and not


Op1 Op2 Op1 and Op2
True True True
True False False
False True False
False False False
Table 2.2. Truth Table of and operator
Op1 Op2 Op1 or Op2
True True True
True False True
False True True
False False False
Table 2.3. Truth Table of or operator
Op1 not Op1
True False
False True
Table 2.4. Truth Table of not operator

Sample Code:
a=True
b=False
print a and b
print a or b
print not a
2.12 Problem Solving and Python Programming

Sample Output:
False
True
False

2.5.1.5 Bitwise Operators


Bitwise operators perform bit by bit operations and numbers are represented as series of 1’s
or 0’s and explained as follows:
Operator Description
& Performs Bitwise AND operation between two the operands.
| Performs Bitwise OR operation between two the operands.
^ Performs Bitwise XOR (exclusive OR) operation between two the operands.
~ Performs Bitwise 1’s complement on a single operand.
<< Shifts the first operand left by the number of bits specified by the second
operand (Bitwise Left Shift).
>> Shifts the first operand right by the number of bits specified by the second
operand (Bitwise Right Shift).

Truth table for &, |, ^ and ~ is given below:


a b a&b a|b a^b ~a
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
Table 2.5. Truth Table of &, |, ^, ~ operator

Sample Code:
a = 60 # 60 = 00111100
b = 26 # 13 = 0001 1010
c = a & b; # 24 = 00011000
print “Result of Bitwise AND is “,
c c = a |b; # 62 = 00111110
print “Result of Bitwise OR is “, c
c = a ^b; # 38 = 00100110
print “Result of Bitwise XOR is “, c
c = ~a; # -61 = 11000011
print “Result of Bitwise Ones Complement is “, c
Data, Expressions, Statements 2.13

c = a << 2; # 240 = 11110000


print “Result of Bitwise Left Shift is “, c
c = a >> 2; # 15 = 00001111
print “Result of Bitwise Right Shift is “, c

Sample Output:
Result of Bitwise AND is 24
Result of Bitwise OR is 62
Result of Bitwise XOR is38
Result of Bitwise Ones Complement is -61
Result of Bitwise Left Shift is240
Result of Bitwise Right Shift is15
2.5.1.6 Membership Operators
Membership operators test whether a value or variable is found in a sequence, such as
strings, lists, or tuples and explained below:

Operator Description
in Evaluatestotrueifitfindsavariableinthespecifiedsequenceandfalseotherwise.
not in Evaluatestotrueifitdoesnotfindsavariableinthespecifiedsequenceandfalse
otherwise.

SampleCode:
a=6
b=2
list = [1, 2, 3, 4, 5 ];
print a in list
print a not in list
print b in list
print b not in list

Sample Output:
False
True
True
False
2.14 Problem Solving and Python Programming

2.5.1.7 Identity Operators


Identity operators compare the memory locations of two objects. They are explained below:
Operator Description
is Returns true if both operands point to the same object and false otherwise.
is not Returns false if both operands point to the same object and true otherwise.

SampleCode:
a = 20
b = 20
print a is b
print id(a) == id(b)
print a is not b
b=30
print a is b
print a is not b
print id(a) == id(b)

Sample Output:
True
True
False
False
True
False
2.5.1.8 Unary arithmetic operators
Operator Description
+ Returns its numeric argument without any change.
- Returns its numeric argument with its sign changed.

SampleCode:
a = 10
b = +a
print b
c = -a
print c
Data, Expressions, Statements 2.15

Sample Output:
10
–10

2.5.3 Operator precedence


When more than one operator appears in an expression, the order of evaluation depends on
therulesofprecedence.Formathematicaloperators,Pythonfollowsmathematicalconvention.The
acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction)
is a useful way to remember therules.

The following table summarizes the operator precedence in Python, from the highest
precedence to the lowest precedence. Operators in the same box have the same precedence and
groupfromlefttoright(exceptforcomparisons,includingtests,whichallhavethesameprecedence and
chain from left to right and exponentiation, which groups from right toleft).

Operator Description Associativity


(expressions...) Binding or tuple display left to right
[expressions...] list display
{key: value...} dictionary display
'expressions...' stringconversion
x[index] Subscription left to right
x[index:index] Slicing
x(arguments...) Call
x.attribute Attribute reference
** Exponentiation right-to-left
+x Unary plus left to right
-x Unaryminus
~x BitwiseNOT
* Multiplication left to right
/ Division
// Floordivision
% Remainder
+ Addition left to right
- Subtraction
<<, >> Bitwise Left Shift and Right left to right
Shift
& Bitwise AND left to right
^ Bitwise XOR left to right
| Bitwise OR left to right
2.16 Problem Solving and Python Programming

in, not in Membership tests Chain from left to right


is, is not Identity tests
<, <=, >, >=, <>, !=, == Comparisons
not Boolean NOT left to right
and Boolean AND left to right
or Boolean OR left to right
Table 2.6. Operator Precedence

Examples:
4 * (6-3) is 12, and (1+2)**(6-3) is 27.
3**1+1 is 4, not 9.
2*1**4 is 2, not 16.
4*6-2 is 22, not 16.
4+2/2 is 5, not 3.
4/2*2 is 4, not 1.

2.6 FUNCTIONS
A function is a group of statements that perform a specific task. If a program is large, it
is difficult to understand the steps involved in it. Hence, it is subdivided into a number of smaller
programs called subprograms or modules. Each subprogram specifies one or more actions to be
performedforthelargerprogram.Suchsubprogramsarecalledasfunctions.Functionsmayormay not
take arguments and may or may not produceresults.

Advantages of Functions
• Decomposinglargerprogramsintosmallerfunctionsmakesprogrameasytounderstand,
maintain and debug.
• Functionsdevelopedforoneprogramcanbereusedwithorwithoutmodificationwhen
needed.
• Reduces program development time and cost.
• It is easy to locate and isolate faulty function.

2.6.1 Types offunctions


2.6.1.1 Built-in/Pre-defined function
Built-in functions are functions already built into Python interpreter and are readily available
for use.

Example:
print() Print objects to the stream.
Reads a line from input, converts it to a string (stripping a trailing newline), and
input()
returns that.
Data, Expressions, Statements 2.17

abs() Return the absolute value of a number.


len() Return the length (the number of items) of an object.

Program to find the ASCII value of the given character.


c = input(“Enter a character”)

print(“ASCII value of “ +c+ “is”+ord(c))

Sample Input/Output:
p

ASCII value of p is 112

ord() function convert a character to an integer (ASCII value). It returns the Unicode
code point of that character.

2.6.1.1.1 Type conversionfunctions


Python provides built-in functions that convert values from one type to another.
Function Converting what to what Example
>>> int(‘2014’)
2014
int() string, floating point → integer
>>> int(3.141592)
3
>>>float(‘1.99’)
string, integer → floating point 1.99
float()
number >>>float(5)
5.0
>>> str(3.141592)
integer, float, list, tuple, dictionary ‘3.141592’
str()
→ string >>> str([1,2,3,4])
‘[1, 2, 3, 4]’
>>>list(‘Mary’) # list of characters in
‘Mary’
list() string, tuple, dictionary → list [‘M’, ‘a’, ‘r’, ‘y’]
>>> list((1,2,3,4)) # (1,2,3,4) is a tuple
[1, 2, 3, 4]
>>> tuple(‘Mary’)
(‘M’, ‘a’, ‘r’, ‘y’)
tuple() string, list → tuple >>>tuple([1,2,3,4]) # [ ] for list, ( ) for
tuple
(1, 2, 3, 4)
>>> age = 21
>>> sign = ‘You must be ‘ + age + ‘Years old’
2.18 Problem Solving and Python Programming

ManyPythonfunctionsaresensitivetothetypeofdata.Forexample,youcannotconcatenate a
string with an integer. If you try, it will result in following error.

Traceback (most recent call last):


File “<pyshell#71>”, line 1, in <module>
sign = ‘You must be ‘ + age + ‘years old’
TypeError: cannot concatenate ‘str’ and ‘int’ objects

For the example above, use the str() conversion function to convert integer to string data
type.
>>> age = 21
>>> sign = “You must be “ + str(age) + “Years old”
>>>sign

Sample Output:
You must be 21 Years old

Examples using Built-in functions for type conversion


Program Code Output
Converting float to int
>>>print(3.14, int(3.14)) 3.14 3
>>>print(3.9999, int(3.9999)) 3.9999 3
>>>print(3.0, int(3.0)) 3.0 3
>>>print(-3.999, int(–3.999)) –3.999 –3
Converting string to int
>>>print("2345", int("2345")) 2345 2345
>>>print(int("23bottles")) Error :
ValueError: invalid literal for int() with
base 10: '23bottles'

Converting int to string


>>>print(str(17)) 17
Converting float to string
>>>print(str(123.45))
>>>print(type(str(123.45))) 123.45
Converting list to tuple
>>>fruits = ['apple', 'orange', 'grapes', <class 'str'>
'pineapple']
('apple', 'orange', 'grapes', 'pineapple')
>>>print(tuple(fruits))
('P', 'y', 't', 'h', 'o', 'n')
>>>print(tuple('Python'))
Converting tuple to list
>>>print(list(‘Python’)) ['P', 'y', 't', 'h', 'o', 'n']

2.6.1.1.2 Python modules:


It is a file which contains group of functions, python definitions and statements.
Two types are there
1. Built in modules
2. User defined module

2.6.1.1.3 Math functions


Math and cmath are mathematical modules available in Python to support familiar
mathematical functions. A module is a file that contains a collection of related functions. Before
using built-in math functions, import math module.

>>>import math

It will create a module object named math which contains functions and variables defined
in the module. Some of the familiar math functions are listed in Table.

Function Description Example Output


abs(n) Return the absolute abs(–99) 99
value of a number(n)
round(n,d) Round a number(n)to round(3.1415,2) 3.14
a number of decimal
points(d)
floor(n) Round down to math.floor(4.7) 4.0
nearest integer
ceil(n) Round up to nearest math.ceil(4.7) 5.0
integer
pow(n,d) Return n raised to the math.pow(10,3) 1000.0
power d
sqrt(n) Returns the square math.sqrt(256) 16.0
root of number(n)
fsum(iterable) Return anaccurate sum([.1, .1, .1, .1,.1, 0.99999999999999
floating point sum of .1, .1, .1, .1, .1])

1.0
factorial(n) Return n factorial math.factorial(5) 120
gcd(n,m) Return greatest math.gcd(10,125) 5
common divisior of
(n,m)
trunc(x) Return the real math.trunc(1.999) 1
value x truncated to
an integral
sin(x), cos(x), Return the arc sine, math.sin(math.pi/4) 0.7071067811865476
tan(x) cosine, tangent of x, math.cos(math.pi) –1.0
in radians.
math.tan(math.pi/6) 0.5773502691896257

Mathematical Constants
• math.pi
The mathematical constant π = 3.141592..., to available precision.
• math.e
The mathematical constant e = 2.718281..., to available precision.

2.6.1.1.4 Random module


Generates random number.
Three functions are there
1. randint(low,high) – to generate random integer , two input parameter
2. random() – to generate random floating point numbers, no input parameter
3. choice() –to generate random elements from the list, a sequence parameter

Example:
import random
print random.randint(1,5)
print random.random()
data=(“cse”,”eee”,”ece”,”civil’,”mech”)
print random.choice(data)

Example
4
20.9
cse

Calendar module – Tracks date and time.


Example:
import calendar
print calendar.month(2015,5)
output
May 2015
Sun mon Tue wed Thurs fri sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

User defined module


Steps
1. Create a python file with one or more functions and save it .py extension.
2. include import statement
3. import modulename1
4. when the interpreter come across import the statement, import the module.
5. Then module is loaded only once even if multiple imports occurs. The module function is
accessed by using (.) dot operator.
Example:
def sum(i,j):
sum=i+j
print sum
the above code is saved as file.py

Another program
import file
file.sum(10,20)

output:
30

2.6.1.2 User definedfunction


The functions defined by the users according to their requirements are called user-defined
functions. The users can modify the function according to their requirements.
Example:
multiply(), sum_of_numbers(), display()
Defining a Function
Functionsinpythonaredefinedusingtheblockkeyworddeffollowedbythefunctionname and
parentheses ( ( ) ). Function definitionincludes:
(1) A header, which begins with a keyword def and ends with acolon.
(2) Input parameters are defined inside these parenthesis.
(3) : colon used to mark end of the function header.
(4) Optional docstring refers what the functions does.
(5) AbodyconsistingofoneormorePythonstatements inside the function have same
indentation 4 space – from theheader.
(6) Optional return statement return a value.

Syntax:
def function_name( parameters ):
“function_docstring”
function_suite
return [expression]
The code block within every function starts with a colon (:) and is indented. The first
statement of a function can be an optional statement - the documentation string of the function or
docstring. The statement return [expression] exits a function, and optionally it returns the result of
the function. The rules for function names are the same as for variable names: letters, numbers and
somepunctuationmarksarelegal,butthefirstcharactercan’tbeanumber.Keywordsshouldnotbe used as
function name. To avoid confusion, use different names for functions andvariables.
Calling a Function
A function can be executed by calling it from another function or directly from the Python
prompt by its name.

Syntax:
function_name(parameters)
Function to display Welcome message.
def display():
print “Welcome!!!”
>>>display()
Sample output:
Welcome!!!
The first line of the function definition is called the header; the rest is called the body. The
header has to end with a colon and the body has to be indented. By convention, the indentation is
alwaysfourspaces.Inthisexample,thefunctionnameisdisplay().Theemptyparenthesesafterthe name
indicate that this function doesn’t take anyarguments.

Function to find the biggest of three numbers.


def great(no1,no2,no3):
if (no1>no2) and (no1>no3):
return no1
elif (no2>no3):
return no2
else:
return no3
n1=input(“Enter first number”)
n2=input(“Enter second number”)
n3= input(“Enter third number”)
result=great(n1,n2,n3)
print result, “is bigger”

Sample Input/Output:
Enter first number 10
Enter second number 5
Enter third number 25
25 is bigger
Inthisexample,thefunctionnameisgreat().Ittakesthreeparametersandreturnthegreatest
ofthree.input()readsinputvaluefromtheuser.Thefunctionisinvokedbycallinggreat(n1,n2,n3). print()
displays the output. The strings in the print statements are enclosed in doublequotes.

Function Definitions and uses


def add(a,b):
return (a+b)
defsub(a,b):
return (a-b)
def calculate():
a=input(“Enter first number”)
b=input(“Enter second number”)
result=add(a,b)
print result
result=sub(a,b)
print result
return
This program contains three function definitions: add(), sub(), and calculate(). Function
definitions are executed to create function objects. The statements inside the function do not get
executeduntilthefunctioniscalled,andthefunctiondefinitiongeneratesnooutput.Functionmust be
created before execution i.e. function definition has to be executed before the first time it is called.

Flow of execution
Flow of execution specifies the order in which statements are executed. Program
execution starts from first statement of the program. One statement is executed at a time from top
to bottom.
Functiondefinitionsdonotaltertheflowofexecutionoftheprogram,andthestatementsinsidethe function
are not executed until the function is called. When a function is called, the control flow
jumpstothebodyofthefunction,executesthefunction,andreturnbacktotheplaceintheprogram where
the function call was made. Python is good at keeping track of where it is, so each time a
functioncompletes,theprogrampicksupwhereitleftoffinthefunctionthatcalledit.Whenitgets to the
end of the program, it terminates.

Parameters and arguments


Arguments are the values provided to the function during the function call. Parameters
are name used inside the function definition to refer to the value passed as an argument. Inside the
function, the value of arguments passed during function call is assigned toparameters.
Function to raise a number to given power
import math # This will import math module
>>>def raise(no,power):
print math.pow(no,power)
>>>a=100
>>>b=2
>>>raise(a,b)
>>>10000

The function raise() assign the argument a, b to parameters no, power.


>>>raise(30,3)
>>>27000
The function raise() assign the values 30, 3 to parameters no, power.

In this example, the arguments used in function call raise() are a, b and their values are
assigned to parameters no,power.

Functions with noarguments


The empty parentheses after the function name indicate that this function doesn’t take any
arguments.

Function to display PI value.


import math
>>>def show_PI():
print math.pi
>>>show_PI()

Sample output:
3.141592653589793

Functions witharguments
Functions may also receive arguments (variables passed from the caller to the function).
Arguments in function call are assigned to function parameters.

Function to calculate area of a circle.


import math
>>>def area_of_circle(r):
a = r * r * math.pi
print “Area of Circle:”, a
>>>radius=input(“Enter Radius:”)
>>>area_of_circle(radius)

Sample output:
Enter Radius:6
Area of Circle:113.04

Functions with return value


Functions may return a value to the caller, using the keyword- ‘return’.

Function to calculate factorial of a given number.


def factorial(num):
fact=1
i=1
if num==0:
return 1
else:
for i in range(1,num+1):
fact=fact*i
return fact
no=input(“Enter a number”)
print(factorial(no))

Sample input/output:
Enter a number:5
120

2.7 Function Arguments


2.7.1 Four types of arguments
• Required arguments
• Keyword arguments
• Default arguments
• Variable length arguments
Required arguments
Number of arguments passed in function call should exactly match the function
definition.
Example:
1. def display(msg):
print msg
print “welcome python”
display(“good morning”)
2. def display(msg1,msg2):
print msg1
print msg2
display ( “good morning “ ,” welcome “ )

Output

good morning
welcome

Keyword arguments:
 The function caller identifies the arguments by the parameter name.
 These values get a assigned to the arguments according to their position.
 The order of the arguments can be changed.
 Mix positioned arguments with key word arguments during function call.
 Keyword arguments must follow positional arguments but reverse not
possible.

Example :
def display (rollno,name=”surya”,sch=”GHSS”,groups=”cs”):
print rollno
print name
print sch
print group
display(cs20)
display(rollno=cs21,name=”sachin”)

output:

cs20e
surya
GHSS
cs
cs21
sachin
GHSS
cs

Default arguments:
It can provide default value to an argument by using theassignment operator.
Arguments assume default value if a value is not provided in the function call.

def display (name,age=17):


printt name
print age
display(age=15,name=”sachin”)
display(name=”dravid”)
output:
sachin
15
dravid
17

Variable length Arguments:


Sometimes the number of arguments that will be passed into a function not known
in advance. Use a asterisk (*) before the parameter name to denote this kind of argument.

Example:
def display(*names):
print names
display(“sachin”,”dravid”,”kapil”)

output:
sachin
dravid
kapil

Lambda function/Anonymous Function:


 This function are not defined like normal function by using keyword def.
 These function are defined using the keyword lambda.
Syntax:
Lambda arguments : expression
Rules for Lambda function:
It can take any number of arguments but returns only ne value in the form of
expressions. They cannot contain commands or multiple expressions. Lambda functions
are single line function. It cannot be a direct call to print because lambda requires an
expression.
Example
sum1=lambda a,b,c : a+b+c
print sum1(2,5,8 )
print sum1(1,2,3)

output:
15
7

2.8 ILLUSTRATIVEPROGRAMS
2.8.1 Function to exchange the values of twovariables
defswap(a,b): # function definition forswapping
tmp=a
a=b
b=tmp
print ‘After Swap: n1=”,a, “n2=”,b
return

n1=input(“Enter first number”)


n2=input(“Enter second number”)
print ‘Before Swap: n1=”,n1,“n2=”,n2
swap(n1,n2) # function call

Sample input/output:
Enter first number1
Enter second number11
Before Swap: n1= 1 n2= 11
After Swap: n1= 11 n2= 1
2.8.2 Python program to test for leapyear
Note: A leap year is divisible by four, but not by one hundred, unless it is divisible by four
hundred.
def leapyr(yr): # functiondefinition
if yr%4==0 and yr%100!=0 or yr%400==0: # condition check for leap year
print ‘LeapYear’
else:
print ‘Not a Leap Year’
return
year=input(“Enter a year”)
leapyr(year) # function call

Sample input/output:
Enter a year1900
Not a Leap Year

2.8.3 Python program to test for leap year using calendarmodule


Python provides this functionality already in the library module ‘calendar’.
import calendar
def leapyr(yr):
if(calendar.isleap(yr)): # Using built-in function to check for leap year
print ‘LeapYear’
else:
print ‘Not a Leap Year’
return
year=input(“Enter a year”)
leapyr(year)

2.8.4 Python function to sum all the numbers in alist


def sum(numbers):
total=0
for x in numbers: # Loop through number
total+=x
return total
print(sum((1,2,3,4,5)))

Sampleoutput:
15
2.8.5 Python program to reverse astring
def string_reverse(str1):
rstr1= “”
index=len(str1)
while index>0:
rstr1+=str1[index-1]
index=index-1
return rstr1
print “Reverse String:”, string_reverse(“Python”)

Sample output:
Reverse String:nohtyP

2.8.6 Python function to check whether a number is in a givenrange


def test_range(n):
if n in range(1,10): # Loop through range of number from 1 upto 10
print “No. is between 1 and 10”
else:
print “No. is not between 1 and 10”
no=input(“Enter a no.”)
test_range(no)
Sample input/output:
Enter a no. 10
No. is not between 1 and 10
Enter a no. 4
No. is between 1 and 10

2.8.7 Python program to print the even numbers from a givenlist


def print_even(l): # l represents list of values
for n in l:
if n % 2 == 0:
print ‘\n’, n
return
print_even([1, 2, 3, 4, 5, 6, 7, 8, 9])

Sample output:
2
4
6
8

2.8.8 Functionthatcirculates/rotatesthelistvaluesforgivennumberoftimes(order)
def rotate(l,order):
for i in range(0,order):
j=len(l)-1
while j>0:
tmp=l[j]
l[j]=l[j-1]
l[j-1]=tmp
j=j-1
print i, ‘rotation ’,l
return
l=[1,2,3,4,5]
rotate(l,3)
Sample output:
0 rotation: [5, 1, 2, 3, 4]
1 rotation: [4, 5, 1, 2, 3]
2 rotation: [3, 4, 5, 1, 2]

2.8.9 Functionthattakesanumberasaparameterandcheckthenumberisprimeor not


Note : A prime number (or a prime) is a natural number greater than 1 and that has no
positive divisors other than 1 and itself.
def test_prime(n): # function that returns boolean value
if(n==1):
return False
elif(n==2):
return True
else:
for x in range(2,n):
if(n%x==0):
return False
return True
no=input(“Enter a number”)
if(test_prime(no)):
print no, ‘is Prime’
else:
print no, ‘is not Prime’
Sample output:
Enter a number9
9 is not Prime
Enter a number11
11 is Prime
2.8.10 Function to check whether a number is perfect ornot
Example : The first perfect number is 6, because 1, 2, and 3 are its proper positivedivisors,
and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: (
1 + 2 + 3 + 6 ) / 2 = 6.
def perfect_number(n): # functiondefinition
sum =0
for x in range(1, n):
if n % x == 0:
sum += x
return sum
no=input(“Enter a number”)
sum=perfect_number(no) # function call
if(sum==no):
print ‘Perfect number’
else:
print ‘Not a Perfect number’

Sample input/output:
Enter a number5
Not a Perfect number
Enter a number6
Perfect number

2.8.11 Function that checks whether a passed string is palindrome ornot


def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >=left_pos:
if string[left_pos] != string[right_pos]:
returnFalse
left_pos += 1
right_pos -= 1
return True
str=raw_input(“Enter a string:”) #use raw_input() to read verbatim string entered
by user
if(isPalindrome(str)):
print str, ‘is a Palindrome’
else:
print str, ‘ is not a Palindrome’

Sample input/output:
Enter a string:madam
madam is a Palindrome
2.8.12 Function that checks whether a number is palindrome ornot
def Palindrome_Number():
no = input(“Enter a Number:”)
q=no
rev = 0
while(q!=0): # loop for reverse
rev = q % 10 + rev * 10
q = q / 10
if( rev == no):
print(‘%d is a palindrome number’ %no)
else:
print(‘%d is not a palindrome number’ %no)
Sample input/output:
Enter a Number121
121 is a palindrome number
2.8.13 Find the distance between two points (xc,yc) and(xp,yp).
import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
xc=int(input("Enter xc"))
yc=int(input("Enter yc"))
xp=int(input("Enter xp"))
yp=int(input("Enter yp"))
print (distance(xc,yc,xp,yp))
Sample input/output:
Enter xc 2
Enter yc 2
Enter xp 4
Enter yp 4
2.82
Data, Expressions, Statements 2.31

TWO MARKS QUESTION & ANSWER


1. What is Python?
Python is a general-purpose, interpreted, interactive, object-oriented, and high-level
programming language. It is derived from many other languages, including ABC, Modula-3,
C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.

2. What are the features of the Pythonlanguage?


• Easy-to-learn: Python has few keywords, simple structure, and a clearly definedsyntax
• Easy-to-read: Python code is more clearlydefined
• Easy-to-maintain: Python’s source code is fairlyeasy-to-maintain.
• Interactive and extendable: Python allows interactive testing and debugging andallows
user to add low-level modules to the PythonInterpreter.
• Portable and scalable: Python can run on a wide variety of hardware platforms and
support for large programs than shellscripting.

3. What are the comment lines inPython?


A comment is a programmer-readable explanation or annotation in the source code of a
computer program. All characters available inside any comment are ignored by interpreter.
Single-line comments are created simply by beginning a line with the hash (#) character, and
they are automatically terminated by the end of line.
Example:
#This would be a comment in Python
Multi-line comments are created by adding a triple quoted string (“””) on each end of the
comment.
Example:
“””
This is a
multilline comment
“””
4. What are the advantages and disadvantages ofPython?
Advantages:
• Python is easy to learn for even a novicedeveloper
• Supports multiple systems andplatforms.
• Object OrientedProgramming-driven
• Allows to scale even the most complex applications withease.
• A large number of resources are available forPython.
2.32 Problem Solving and Python Programming

Disadvantages:
• Python isslow.
• Has limitations with databaseaccess.
• Python is not good for multi-processor/multi-corework.

5. Defineoperator.
An operator is a special symbol that asks the compiler to perform particular mathematical
or logical computations like addition, multiplication, comparison and so on. The values the
operator is applied to are called operands.

6. Categorize the operators of Python.


Python language supports the following types of operators.
• ArithmeticOperators
• Comparison (Relational)Operators
• AssignmentOperators
• LogicalOperators
• BitwiseOperators
• MembershipOperators
• IdentityOperators
• Unary arithmeticOperators

7. What is the difference between * operator and **operator?


* is a multiplication operator which multiplies two operands.
Eg. 2*3 returns 6.
** is an exponent operator that performs exponential (power) calculation.
Eg. 2**3 returns 8.

8. What is the difference between = and ==operator?


= is an assignment operator and == is a relational operator.
== operator returns true, if the values of two operands are equal.
= operator assigns values from right side operand to left side operand.

9. Give the use of identity operators inPython?


Identity operators compare the memory locations of two objects. There are two identity
operators in Python:
• is operator returns true if both operands point to the sameobject.
• Is not operator returns false if both operands point to the sameobject.
Data, Expressions, Statements 2.33

10. What is the difference between unary operator and binaryoperator?


unary operator binary operator
Used with single operand. Used with two operands.
Eg: +, -, <, is. Eg: +, -.
11. What is the need of operatorprecedence?
When more than one operator appears in an expression, the order of evaluation is determined
by the rules of operator precedence.

12. What is the output of the following Pythonprogram?


x=6
y = 4
print(x/y)
Output: 1.5

13. Define keyword. List few Pythonkeywords.


Keywords are certain reserved words that have standard and pre-defined meaning in Python.
We cannot use a keyword as variable name, function name or any other identifier.
Example. False, class, finally, nonlocal, yield, lambda, assert.

14. What is a variable?


Variablesarereservedmemorylocationstostorevalues.Avariableisanidentifierformemory
location.
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.
Example:
counter = 100 # An integerassignment
miles = 1000.0 # A floatingpoint
name = “John” # Astring

15. What ate the data types available inPython?


Python has five standard data types :
• Numbers (int, long, float,complex)
• String
• List
• Tuple
• Dictionary
2.34 Problem Solving and Python Programming

16. Write any 6 escape sequences inPython.


\n – move to next line
\t – move one space horizontally
\v- move in space vertically
\f – move to next page
\r – move to starting of that line
\b – backspace

17. What is type casting?


Type casting is the process of converting the value of an expression to a particular data type.
This is, in Python, done with functions such as int() or float() or str().
Example:
x = ‘100’
y = ‘-90’
print x + y
Output: 100-90

print int(x) + int(y)


Output: 10

18. Write in short about relationaloperators.


Relationaloperatorsareusedtocompareanytwovalues.Anexpressionwhichusesarelational
operator is called a relational expression. The value of a relational expression is either true or
false.
Example: = =, !=,>, <
3>4
Output: False

19. What are the Bitwise operators available inPython?


& - Bitwise AND
| - Bitwise OR
~ - One’s Complement
>> - Right shift
<< - Left shift
^ - Bitwise XOR are called bit field operators
Example: k=~j; where ~ take one’s complement of j and the result is stored in k.
Data, Expressions, Statements 2.35

20. Definefunction.
A function is a self-contained program, or a sub-program of one or more statements which is
used to do some particular task.
Types of functions: i)User defined, ii)pre-defined

21. What are pre-defined functions? Giveexample.


Pre-defined functions or Built-in functions are functions already built into Python interpreter
and are readily available for use.
Example: print(), abs(), len()

22. What is RETURN statement?


Itisusedtoreturnthecontrolfromcallingfunctiontothenextstatementintheprogram.Itcan also return
somevalues.
Example: return, return 0, return (a+b)
2.36 Problem Solving and Python Programming

PYTHONDOWNLOAD
AND INSTALLATIONINSTRUCTIONS

Visit python.org/download/ and download the appropriate Python 3 Windows installer for
your architecture (32-bit and 64-bit). The following are the steps involved in downloading and
installing Python 3.4.3 version on Windows 7. The current version available is Python 3.6.2. The
Pythondownload requires about24Mbofdiskspace;keepitonyourmachine,incaseyouneedto re-
install Python. When installed, Python requires about an additional 50 Mb of diskspace.

DOWNLOADING
(1) Visit https://www.python.org/downloads/. The following page will appear in your
browser.

(2) Click the Download Python 3.4.3button.


Thefilenamedpython-3.4.3.msishouldstartdownloadingintoyourstandarddownload
folder. The file should appearas

(3) Movethisfiletoamorepermanentlocation,sothatyoucaninstallPython(andreinstall it later,


ifnecessary).
(4) Start the Installing instructions directlybelow.
2 Problem Solving and Python Programming

Installing on Microsoft Windows


(1) Double-click the icon labeling the filepython-3.4.3.msi.
An Open File - Security Warning pop-up window will appear.

(2) Click Run.


A Python 3.4.3 Setup pop-up window will appear.

Ensure that the Install for all users radio button is pressed.
(3) Click Next >button.
A new Python 3.4.3 Setup pop-up window will appear (Select Destination Directory).

Note that if you have installed an earlier version of Python 3.4, the following pop-up
window will appear.
Python Download And Installation Instructions 3

Click the Yes button to use the newest installation. The default directory will appear in
thebottomasC:\Python34\andunlessyouhaveagoodreasontouseanotherdirectory, use
this one.

(4) Click the Next >button.


A new Python 3.4.3 Setup pop-up window will appear (Customize Python 3.4.3).

Use the default customization, which selects the Python Interpreter and all its libraries
(about 42 Mb).

(5) Click the Next >button.


Inafewsecondsapop-upwindowtitledUserAccountControlwillappear,posingthe
question Do you want the following program to install software on thiscomputer?

(6) Click the Yesbutton.


A new Python 3.4.3 Setup pop-up window will appear (Install Python 3.4.3).
4 Problem Solving and Python Programming

During installation, it will show the various operations it is performing and a progress
bar for each one. It might temporarily pop-up a small window in which to execute
commands.

Eventually a new Python 3.4.3 Setup pop-up window will appear (Complete the
Python 3.4.3 Installer).

(7) Click the Finishbutton.


Python should now be installed. To try to verify installation, navigate to the directory
Python Download And Installation Instructions 5

C:\Python34(ortowhateverdirectoryonwhichyouinstalledPython)double-clickthe
icon/file python.exe. The following pop-up window willappear.

A pop-up window with the title C:\Python34\python.exe appears, and inside the
window on the first line is the text Python 3.4.3 ... (notice that it should say 32 bit).
Inside the window, at the bottom left, is the prompt >>>: type exit() to this prompt and
pressentertoterminatePython.Youshouldkeepthefilepython-3.4.3.msisomewhere on
your computer in case you need to reinstall Python (not likely necessary).

Installing on Ubuntu Linux


ModernLinuxdistributionsarebackedbyvastrepositoriesofprecompiledapplications,
readytoinstall.Theexactdetailsvarybydistribution.InUbuntuLinux,theeasiestway to
install Python 3 is through the Add/Remove application in your Applicationsmenu.

WhenyoufirstlaunchtheAdd/Removeapplication,itwillshowyoualistofpreselected
applications in different categories. Some are already installed; most are not. Because
the repository contains over 10,000 applications, there are different filters you can
apply to see small parts of the repository. The default filter is “Canonical-maintained
applications,”whichisasmallsubsetofthetotalnumberofapplicationsthatareofficially
supported by Canonical, the company that creates and maintains Ubuntu Linux.

Python3isnotmaintainedbyCanonical,sothefirststepistodropdownthisfiltermenu and
select “All Open Source applications.”
6 Problem Solving and Python Programming

Once you’ve widened the filter to include all open source applications, use the Search
box immediately after the filter menu to search for Python 3.

Now the list of applications narrows to just those matching Python 3. You’re going to
check two packages. The first is Python (v3.0). This contains the Python interpreter
itself.

The second package you want is immediately above: IDLE (using Python-3.0).
Afteryou’vecheckedthosetwopackages,clicktheApplyChangesbuttontocontinue.
Python Download And Installation Instructions 7

The package manager will ask you to confirm that you want to add both IDLE (using
Python-3.0)and Python (v3.0). Click the Applybutton to continue.

Thepackagemanagerwillshowyouaprogressmeterwhileitdownloadsthenecessary
packages from Canonical’s Internetrepository.

Once the packages are downloaded, the package manager will automatically begin
installing them.

Ifallwentwell,thepackagemanagerwillconfirmthatbothpackagesweresuccessfully
installed.Fromhere,youcandouble-clickIDLEtolaunchthePythonShell,orclickthe Close
button to exit the package manager. You can always relaunch the Python Shell
bygoingtoyourApplicationsmenu,thentheProgrammingsubmenu,andselecting
IDLE.
GE8161 PROBLEM SOLVING AND PYTHON L T PC
PROGRAMMING LABORATORY 0042

OBJECTIVES
• To write, test, and debug simple Pythonprograms.
• To implement Python programs with conditionals andloops.
• Use functions for structuring Pythonprograms.
• Represent compound data using Python lists, tuples,dictionaries.
• Read and write data from/to files inPython.

LIST OF PROGRAMS
(1) Compute the GCD of twonumbers.
(2) Find the square root of a number (Newton’smethod)
(3) Exponentiation (power of a number)
(4) Find the maximum of a list ofnumbers
(5) Linear search and Binarysearch
(6) Selection sort, Insertionsort
(7) Mergesort
(8) First n primenumbers
(9) Multiplymatrices
(10) Programs that take command line arguments (wordcount)
(11) Find the most frequent words in a text read from afile
(12) Simulate elliptical orbits inPygame
(13) Simulate bouncing ball usingPygame

PLATFORM NEEDED
Python 3 interpreter for Windows/Linux

OUTCOMES
Upon completion of the course, students will be able to:
• Write, test, and debug simple Pythonprograms.
• Implement Python programs with conditionals andloops.
• Develop Python programs step-wise by defining functions and callingthem.
• Use Python lists, tuples, dictionaries for representing compounddata.
• Read and write data from/to files inPython.

TOTAL: 60 PERIODS
APPENDIX -A

LABPROGRAMS

(Python 3 interpreter for Windows/Linux)

1. Compute the GCD of twonumbers


Note:thegreatestcommondivisor(GCD)oftwoormoreintegers,whicharenotallzero,is the
largest positive integer that divides each of the integers. For example, the gcd of 8 and 12 is4.

Using Recursion.
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
print (gcd(8,12))

Sample Output:
4
Using built-in functions.
from fractions import gcd
print (gcd(20,8))

Sample Output:
4

Using Non-recursion.
def gcd(x,y):
while y!=0:
(x,y)=(y,x%y)
return x
n1=int(input(‘Enter first number:’))
n2=int(input(‘Enter second number:’))
App-A.2 Problem Solving and Python Programming

print gcd(n1,n2)

Sample Output:
Enter first number:15
Enter second number:11
1

2. Find the square root of a number (Newton’smethod)


Consider the problem of finding the square root of a number. Newton’s method is one of
many methods of computing square root..

For example, if one wishes to find the square root of 612, this is equivalent to finding the
solution to

x2=612

The function to use in Newton’s method is then f(x) = x 2-612 with derivate f’(x)=2x.

With an initial guess of 10, the sequence given by Newton’s method is


2
f(x) 10 612
x x 0 10 35.6
1
f(x0) 210
2
f(x ) 35.6 612
x2 x1 1 35.6  26.395 505 617978...
f(x1) 235.6
x3     24.790635492455...
x4     24.738688294075...
x5      24.738633753767..
where the correct digits are underlined. With only a few iterations one can obtain a solution
accurate to many decimal places.

n=float(input(“What number would you like to square root ?”))


x=float(input(“Estimate your answer”))
final=(0.5*(x+(n/x)))
print(final)
for i in range(0,10):
final=(0.5*(final+(n/final)))
print(str(final))
Sample Output:
What number would you like to square root? 612
Estimate your answer10
35.6
26.395505618
24.7906354925
24.7386882941
24.7386337538
24.7386337537
24.7386337537
24.7386337537
24.7386337537
24.7386337537
24.7386337537

3. Exponentiation (power of anumber)


Given a positive integer n, find if it can be expressed as x^y where y > 1 and x > 0. x and y
both are integers.

import math
n=int(input(“Enter n”))
m=int(input(“Enter m”))
i=1
res=1
whilei<=m:
res*=n
i+=1
print (str(n)+ ‘^’+str(m)+ ‘=’+str(res))
print (str(math.pow(n,m))) #using built-in function

Sample Output:
Enter n 3
Enter m 4
3 ^ 4 =81
81.0
4. Find the maximum of a list ofnumbers
def myMax(L): # function with list as arguments
answer =None
for i in L:
if i > answer:
answer = i
return answer
l=input(‘Enter list of numbers’) # reads list as input
print ‘Maximum is’,myMax(l)

Sample input/output:
Enter list of numbers[1,12,34,11,56]
Maximum is 56

Python 3 code:
score = list(map(int, input(“Enter list of numbers”).split()))
print (“Maximum is”+ str(max(score)))

Sampleinput/output:
Enter list of numbers 1 2 4 5 3
Maximumis5

5. Linear search and Binarysearch


Python program for Linear/ Sequential search.
defseq_search(List,item): # functiondefiniton
pos=0
found=False
while pos<len(List) andnotfound: # loop through the list elements
if(int(List[pos])==item):
found=True
pos=pos+1
return(found,pos)
ls=[ ]
n=int(input(“Enter no. of elements in the list”)) # read n
for i in range(0,n):
v=int(input(“Enter no.”)) # read the number
ls.append(v) # add the no to list
print(ls)
key=int(input(“Enter key tobesearched”)) # lead key value
print(seq_search(ls,key)) # functioncall

Sample input/output:
Enter no. of elements in the list 3
Enter no. 1
Enter no. 2
Enter no. 3
[‘1’, ‘2’, ‘3’]
Enter key to be searched 2
(True, 2)

Python program for binary search.


def binary_search(item_list,item): # functiondefinition
first=0 # set firstposition
last = len(item_list)-1 # set last position
found =False
while( first<=last and not found):
mid = (first+last)//2 # compute middle position
if item_list[mid] == item : # if value is in middle
found =True
else:
if item < item_list[mid]: # check for left half of the list
last = mid - 1
else:
first = mid + 1
return found

print(binary_search([1,2,3,5,8], 6)) # function call


print(binary_search([1,2,3,5,8], 5))
Sample input/output:
False
True

6. Selection sort, Insertionsort


Python program for selection sort
arr=[]
n=int(input(“Enter number of elements”))
for i in range(0,n): # add 'n elements inlist
x=int(input(“Enter number”))
arr.insert(i,x)
i+=1
for i in range(len(arr)):
for j in range(i, len(arr)):
if(arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
print (“Sorted List:”)
print (arr) # print sortedlist

Sample input/output:
Enter no5
enter no.12
enter no. 2
enter no.23
enter no. 4
enter no.5
Sorted List:
[2, 4, 5, 12, 23]

Python program for insertion sort


def insertionsort(list): # functiondefinition
for i in range(1,len(list)):
temp=list[i]
j=i-1
while temp<+list[j] and j>=0:
list[j+1]=list[j]
j=j-1
list[j+1]=temp
return list # return sortedlist
arr=[]
n=int(input(“Enter number of elements”))
for i in range(0,n):
x=int(input(“Enter number”))
arr.insert(i,x)
i+=1
print(insertionsort(arr)) # functioncall

Sample input/output:
Enter number of elements5
Enter number12
Enter number23
Enter number4
Enter number16
Enter number34
[4, 12, 16, 23, 34]

7. Merge sort, Quicksort


Python program for merge sort
def mergeSort(alist):
print(“Splitting “,alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print(“Merging “,alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

Sample output:
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Merging [54]
Splitting [26]
Merging [26]
Merging [26, 54]
Splitting [93, 17]
Splitting [93]
Merging [93]
Splitting [17]
Merging [17]
Merging [17, 93]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Merging [77]
Splitting [31]
Merging [31]
Merging [31, 77]
Splitting [44, 55, 20]
Splitting [44]
Merging [44]
Splitting [55, 20]
Splitting [55]
Merging [55]
Splitting [20]
Merging [20]
Merging [20, 55]
Merging [20, 44, 55]
Merging [20, 31, 44, 55, 77]
Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]

Python program for quick sort


# divide part of the algorithm
def partition(myList, start, end):
pivot = myList[start]
left = start+1
right = end
done = False
while not done:
while left <= right and myList[left] <= pivot:
left = left + 1
while myList[right] >= pivot and right >=left:
right = right -1
if right < left:
done= True
else:
# swap places
temp=myList[left]
myList[left]=myList[right]
myList[right]=temp
# swap start with myList[right]
temp=myList[start]
myList[start]=myList[right]
myList[right]=temp
return right
# conquer part of the quicksort routine
def quicksort(myList, start, end):
if start < end:
# partition the list
pivot = partition(myList, start, end)
# sort both halves
quicksort(myList, start, pivot-1)
quicksort(myList, pivot+1, end)
return myList
List = [54,26,93,17,77,31,44,55,20]
print(quicksort(List,0,len(List)-1))

Sample Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Appendix -A Lab Programs App-A.11

8. First n primenumbers
def primes(n): # functiondefinition
out = list() # declare a list for prime number
for num in range(1, n+1): # loop iterates from 1 upto n+1
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
out.append(num) # if number is prime, add it to list
return out
n=int(input(“Enter a number”)) # read a number
print primes(n) # functioncall

Sample input/output:
Enter a number20
[1, 2, 3, 5, 7, 11, 13, 17, 19]

9. Multiply matrices #
3x3 matrix a
= [[2,3,5],
[13,7,9],
[5,9,4]]
# 3x4 matrix
b =[[4,7,1,8],
[6,2,7,9],
[8,3,2,6]]
# result is 3x4
c = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of a
for i in range(len(a)):
# iterate through columns of b
App-A.12 Problem Solving and Python Programming

for j in range(len(b[0])):
# iterate through rows of c
for k in range(len(b)):
c[i][j] += a[i][k] * b[k][j]
for r in c:
print(r)

Sample Input/Output:
[66, 35, 33, 73]
[166, 132, 80, 221]
[106, 65, 76, 145]

10. Programs that take command line arguments (word count)


#Source filename - wordcount.py; input filename – file1.txt
importsys
if len(sys.argv)!=2:
print ‘Error: Filename missing’
sys.exit(1)
filename=sys.argv[1] # store filename
file=open(filename,”r+”) # open file in readmode
wordcount={} # declare an empty map represently (word, count)
for word in file.read().split():
if word not in wordcount:
wordcount[word]=1 # if word not exists in map add (word, 1) in map)
else:
wordcount[word]+=1 # if word exists, simply increment itscount
for k,v in wordcount.items():
print k, v
Now run the above script as follows.
$ python wordcount.py file1.txt

Sample Input/Output:
This 1
program 2
example 1
Python 2
Appendix -A Lab Programs App-A.13

11. Find the most frequent words in a text read from afile
file=open(“sample.py”,”r+”)
wordcount={}
num_chars=0
for word infile.read().split():
num_chars+=len(word)
if word not in wordcount:
wordcount[word] =1
else:
wordcount[word] += 1
print(‘Number of characters:”+str(num_chars))
for k,v in wordcount.items():
print (str(k)+ ‘-’+ str(v))
file.close()

Sample Output:
Number of characters:109
This-6
is-6
an-6
example-6
Python-2
Testing-1

12. Simulate elliptical orbits inPygame


#Source: https://github.com/stallamraju/SolarSystem
SolarColorPalette.py – To define color for each planet
# Define some basic colors
black = (0, 0, 0)
yellow = (255, 255, 0)
white = (255, 255,255)
#planet colors
App-A.14 Problem Solving and Python Programming

#mercury
mercuryColor = (222,184,135)
#venus
venusColor = (215, 212, 207)
#earth
earthColor = (165, 190, 231)
#mars
marsColor = (232, 193, 135)
#jupiter
jupiterColor = (180, 164, 156)
#saturn
saturnColor = (193, 184, 83)
#uranus
uranusColor = (166, 193, 213)
#neptune
neptuneColor = (144, 174, 224)
Planet.py
class planet:
name = ''
hasRing =False
color = (255, 255, 255) #default to white
#inital position
x=0
y=0
radius = 200 #radius of orbit
speed = 2 #default rate of change of angle
angle = 0 #initial angle to 0
width = 10 #size of planet in width
definit(self, nameOfPlanet):
self.hasRing = False
self.name = nameOfPlanet
self.width = 10
self.color = (255, 255, 255) #default to white
Appendix -A Lab Programs App-A.15

#inital position
self.x =0
self.y =0
self.radius = 200 #radius of orbit
self.speed = 2 #default rate of change of angle
self.angle = 0 #initial angle to 0
#accessor methods
def getColor(self):
return self.color
def setColor(self,inputColor):
self.color = inputColor
return True
def setX(self,xIn):
self.x = xIn
return True
def setY(self,yIn):
self.y = yIn
return True
defgetX(self):
return self.x
defgetY(self):
return self.y
def setRadius(self,radIn):
self.radius = radIn
return True
def getRadius(self):
return self.radius
def getNextAngle(self):
self.angle = self.angle + self.speed
if self.angle > 360:
self.angle -= 360
angleRad = self.angle * 0.0174532925
return angleRad
App-A.16 Problem Solving and Python Programming

def setSpeed(self,sIn):
self.speed = sIn
return True
def getSpeed(self):
return self.speed
defgetAngle(self):
return self.angle
def setAngle(self,aIn):
self.angle = aIn
return True
def getName(self):
return self.name
def setWidth(self, wIn):
self.width = wIn
return True
defgetWidth(self):
return self.width
defhasRings(self):
return self.hasRing
def toggleRings(self):
self.hasRing = not self.hasRing
Solar.py
import pygame
import math
import solarColorPalette
from planet import planet
pygame.init()
# Set the width and height of the screen [width, height]
screenWidth = 1024
screenHeight = 768
screenWidthHalf = screenWidth // 2
screenHeightHalf = screenHeight // 2
size = (screenWidth, screenHeight)
Appendix -A Lab Programs App-A.17

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Solar System") #set title
#logo = pygame.image.load("solar.gif") #set logo of program
#pygame.display.set_icon(logo)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
#initialize planets
#mercury
mercury = planet('Mercury')
mercury.setColor(solarColorPalette.mercuryColor)
mercury.setWidth(3)
mercury.setRadius(50)
mercury.setSpeed(4.5)
mercury.setX(50)
mercury.setY(250)
#venus
venus = planet('Venus')
venus.setColor(solarColorPalette.venusColor)
venus.setWidth(7)
venus.setRadius(100)
venus.setSpeed(4)
venus.setX(100)
venus.setY(250)
#earth
earth = planet('Earth')
earth.setColor(solarColorPalette.earthColor)
earth.setWidth(6)
earth.setRadius(150)
earth.setSpeed(3)
earth.setX(150)
earth.setY(250)
App-A.18 Problem Solving and Python Programming

#mars
mars = planet('Mars')
mars.setColor(solarColorPalette.marsColor)
mars.setWidth(5)
mars.setRadius(180)
mars.setSpeed(2.5)
mars.setX(180)
mars.setY(250)
#jupiter
jupiter = planet('Jupiter')
jupiter.setColor(solarColorPalette.jupiterColor)
jupiter.setWidth(15)
jupiter.setRadius(250)
jupiter.setSpeed(2)
jupiter.setX(250)
jupiter.setY(250)
#saturn
saturn = planet('Saturn')
saturn.setColor(solarColorPalette.saturnColor)
saturn.setWidth(10)
saturn.setRadius(280)
saturn.setSpeed(2.3)
saturn.setX(280)
saturn.setY(250)
saturn.toggleRings()
#uranus
uranus = planet('Uranus')
uranus.setColor(solarColorPalette.uranusColor)
uranus.setWidth(9)
uranus.setRadius(320)
uranus.setSpeed(1.8)
uranus.setX(320)
uranus.setY(250)
Appendix -A Lab Programs App-A.19

#neptune
neptune = planet('Neptune')
neptune.setColor(solarColorPalette.neptuneColor)
neptune.setWidth(8)
neptune.setRadius(350)
neptune.setSpeed(1.2)
neptune.setX(350)
neptune.setY(250)
def drawPlanets(planetIn):
pygame.draw.circle(screen, solarColorPalette.white, [screenWidthHalf,screenHeig
htHalf], planetIn.getRadius(), 1)
pygame.draw.circle(screen, planetIn.getColor(), [planetIn.getX(), planetIn.getY()],
planetIn.getWidth(), planetIn.getWidth())
if planetIn.hasRings() == True:
pygame.draw.circle(screen, solarColorPalette.white, [planetIn.getX(),planetIn.
getY()], planetIn.getWidth()+5, 1)
def movePlanets(planetIn):
angl = planetIn.getNextAngle()
planetIn.setX(int(screenWidthHalf + math.sin(angl) * planetIn.getRadius()))
planetIn.setY(int(screenHeightHalf + math.cos(angl) * planetIn.getRadius()))

# -------- Main Program Loop -----------


while not done:
#----Main eventloop
for event in pygame.event.get():
if event.type ==pygame.QUIT:
done = True
# drawing
screen.fill(solarColorPalette.black)
#sun
pygame.draw.circle(screen, solarColorPalette.yellow, [screenWidthHalf,
screenHeightHalf], 40, 40)
#mercury
drawPlanets(mercury)
App-A.20 Problem Solving and Python Programming

#venus
drawPlanets(venus)
#earth
drawPlanets(earth)
#mars
drawPlanets(mars)
#jupiter
drawPlanets(jupiter)
#saturn
drawPlanets(saturn)
#uranus
drawPlanets(uranus)
#neptune
drawPlanets(neptune)
#Moving the planets along orbit
#mercury
movePlanets(mercury)
#venus
movePlanets(venus)
#earth
movePlanets(earth)
#mars
movePlanets(mars)
#jupiter
movePlanets(jupiter)
#saturn
movePlanets(saturn)
#uranus
movePlanets(uranus)
#neptune
movePlanets(neptune)
pygame.display.flip()
# --- Limit to 120 frames per second
Appendix -A Lab Programs App-A.21

clock.tick(120)
pygame.quit()

13. Simulate bouncing ball usingPygame


import pygame, sys, time, random
from pygame.locals import *
from time import *
pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)#create a 500 * 400
pixel window
pygame.display.set_caption("Bounce") # set window title as “Bounce” and display
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
info =pygame.display.Info()
sw =info.current_w
sh = info.current_h
y=0
# Initial direction is down
direction = 1
while True:
windowSurface.fill(BLACK) #change the background color to black
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0) # draw a circle on
screen
#print "Drawing at 250,", y
sleep(.006) # suspend execution for .006 seconds
y += direction
if y >= sh:
# Changes the direction from down to up
direction = -1
elif y <= 0:
# Changes the direction from up to down
App-A.22 Problem Solving and Python Programming

direction = 1
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT: #window persists until the user close the window
pygame.quit()
sys.exit()
Sample output:

14. Removing all the duplicate elements in alist


Method 1:
def remove_duplicates(x):
a=[ ] # declare a new empty list
for i in x:
if i not in a: # if element not exists in the list, add it
a.append(i)
return a # return list
print (remove_duplicates([1,2,2,3,3,4]))

Sample Output:
[1, 2, 3, 4]

Method 2:
mylist=input(“Enter list of values”)
cleanlist=[]
[cleanlist.append(x) for x in mylist if x not in cleanlist]
print (cleanlist)

Sample Input/Output:
Enter list of values 1 1 2 2 3 3 4 5 5
[1, 2, 3, 4, 5]
APPENDIX-B

SOLVED PROGRAMS INPYTHON

DATA TYPES, VARIABLES AND CONSTANTS

1. Convert the temperature given in Farenheit toCelsius


f=int(input(‘Enter temperature in Farenheit’))
c=5.0/9.0*(f-32)
print (“Temperature in Celsius is”,c)

Sample Input/Output:
Enter temperature in Farenheit 106
Temperature in Celsius is 41.11

2. Find the area and circumference of a circle with radiusr


r=int(input(‘Enter raidus of circle’))
cir=2*22.0/7*r
area=22.0/7*r*r
print (“Circumference of circle:”,cir)
print (“Area of circle:”,area)

Sample Input/Output:
Enter raidus of circle 5
Circumference of circle: 31.428
Area of circle: 78.571

3. Find the average of three


numbers n1=int(input(‘Enter first
number’)) n2=int(input(‘Enter second
number’)) n3=int(input(‘Enter third
number’)) avg=(n1+n2+n3)/3
App-B.2 Problem Solving and Python Programming

print (“Average:”,avg)

Sample Input/Output:
Enter first number 12
Enter second number 11
Enter third number 14
Average: 12.33

4. Simple interest and the maturityamount


p=int(input(‘Enter Principal’))
ri=int(input(‘Enter rate of interest’))
t=int(input(‘Enter time period’))
i=p*ri*t/100
amt=p+i
print (“Interest:”,i)
print(“Amount:”,amt)

Sample Input/Output:
Enter Principal 1000
Enter rate of interest 7
Enter time period 2
Interest: 140
Amount: 1140

5. Find area of a triangle whose sides are a,b, andc


import math
a=int(input(‘Enter side 1 of triangle’))
b=int(input(‘Enter side 2 of triangle’))
c=int(input(‘Enter side 3 of triangle’))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print (“Area:”,area)
Appendix-B Solved Programs in Python App-B .3

Sample Input/Output:
Enter side 1 of triangle 12
Enter side 1 of triangle 5
Enter side 1 of triangle 14
Area: 29.23

DECISION-MAKING AND LOOPING STATEMENTS

6. Check whether a given number is even or odd without using modulusoperator


no=int(input(‘Enter a number’))
if (no&1)==0:
print (“Even”)
else:
print (“Odd”)

Sample Input/Output:
Enter a number 12
Even

7. Find the sum of individual digits in a given positive integernumber


no=int(input(‘Enter a number’))
sum=0
while no>0:
rem=no%10
sum=sum+rem
no=no//10
print (“Sum of digits:”,sum)

Sample Input/Output:
Enter a number 123
Sum of digits: 6
App-B.4 Problem Solving and Python Programming

8. Find the reverse of a given number


no=int(input(‘Enter a number’))
rev=0
while no>0:
rem=no%10;
rev=rev*10+rem
no=no//10
print (“Reverse :”,rev)

Sample Input/Output:
Enter a number 123
Reverse: 321

9. Check whether a given number is a palindrome ornot


no=int(input(‘Enter a number’))
temp=no
rev=0
while no>0:
rem=no%10;
rev=rev*10+rem
no=no//10
if rev==temp:
print (“Palindrome”)
else:
print(“Not a Palindrome”)

Sample Input/Output:
Enter a number 123
Not a Palindrome

10. Check whether a given number is perfect ornot


Annumberisperfectifitsfactors(including1)sumtothenumber.Forexample,6isperfect number
as 6=1+2+3.
no=int(input(‘Enter a number’))
sum=0
Appendix-B Solved Programs in Python App-B .5

for i in range(1,no):
if no%i==0:
sum=sum+i
if no==sum:
print(“Perfect number”)
else:
print(“Not a Perfect number”)

Sample Input/Output:
Enter a number 28
Perfect number

11. Check whether a given number is an Armstrong number ornot


A number is Armstrong if the sum of cube of its digits equals to the number. For example,
153 is an Armstrong number as 13+53+33=153.

no=int(input(‘Enter a number’))
tmp=no
sum=0
while no>0:
rem=no%10
sum=sum+rem*rem*rem
no=no//10
if sum==tmp:
print (“Armstrong Number”)
else:
print(“Not a Armstrong Number”)

Sample Input/Output:
Enter a number 153
Armstrong number

12. Fibonacciseries
no=int(input(‘Enter a number’))
a=0
b=1
App-B.6 Problem Solving and Python Programming

cnt=2
print(a)
print(b)
while cnt<no:
c=a+b
print(c)
a=b
b=c
cnt=cnt+1
Sample Input/Output:
Enter a number 5
0
1
1
2
3

13. Find the sum of all numbers in the range 1 andn


no=int(input(‘Enter a number’))
sum=0
for i in range(1,no+1):
if i%2==1:
sum=sum+i
print (sum)

Sample Input/Output:
Enter a number 5
9

14. Find the sum of series 12+22+…+n2terms


no=int(input(‘Enter a number’))
sum=0
i=1
while i<=no:
sum=sum+i*i
Appendix-B Solved Programs in Python App-B .7

i=i+1
print(“Sum:”,sum)

Sample Input/Output:
Enter a number 5
55

15. Find the sum of series 1+1/2+1/3+…+1/nterms


no=int(input(‘Enter a number’))
sum=0
i=1
while i<=no:
sum=sum+(1/i)
i=i+1
print(“Sum:”,sum)
Sample Input/Output:
Enter a number 5
2.8333

16. Print pyramid of stars as shown below for n number oflines


*
**
***
****
n=int(input(‘Enter a number’))
for i in range(0, n):
for j in range(0, i+1):
print(“* “,end=””)
print(“\r”)
Sample Input/Output:
Enter a number 4
*
**
***
****
App-B.8 Problem Solving and Python Programming

17. Print pyramid of stars as shown below for n number oflines


*
**
***
****
*****
n=int(input(‘Enter a number’))
k = 2*n - 2
for i in range(0, n):
for j in range(0, k):
print(end=” “)
k=k-1
for j in range(0, i+1):
print(“* “, end=””)
print(“\r”)

Sample Input/Output:
Enter a number 4
*
**
***
****

18. Print pyramid of digits as shown below for n number oflines


1
12
123
1234
12345
n=int(input(‘Enter a number’))
num = 1
for i in range(0, n):
num = 1
Appendix-B Solved Programs in Python App-B .9

for j in range(0, i+1):


print(num, end=” “)
num = num + 1
print(“\r”)

Sample Input/Output:
Enter a number 4
1
12
123
1234

19. Write a program that prints the integers between 1 and n which are divisible
by 3, but not divisible by4
n=int(input(‘Enter a number’))
i=1
while i<=n:
if (i%3==0 and i%4!=0):
print(i)
i=i+1

Sample Input/Output:
Enter a number 10
3
6
9

ARRAYS
20. Find the maximum and minimum element in a set ofelements
from array import *
myArray = array(‘i’, [10,2,13,44,5])
maxi=myArray[0]
mini=myArray[0]
for i in myArray:
App-B.10 Problem Solving and Python Programming

if(i>maxi):
maxi=i
elif(i<mini):
mini=i
print(“Minimum:”,mini)
print(“Maximum:”,maxi)

Sample Input/Output:
Minimum:2
Maximum:44

21 Given a list of n numbers, arrange them in ascending order using Bubble


sort.
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
-2 45 0 11 -9 -2 0 11 -9 45 -2 -9 0 11 45
-2 0 -9 11 45

-2 45 0 11 -9 -2 0 11 -9 45 -9 -2 0 11 45
-2 0 -9 11 45

-2 0 45 11 -9 -2 0 11 -9 45 -2 -9 0 11 45

-2 0 11 45 -9 -2 0 -9 11 45

-2 0 11 -9 45

Step1 Step2 Step3 Step4

def bubblesort( A ):
for i in range( len( A ) ):
for k in range( len( A ) - 1, i, -1 ):
if ( A[k] < A[k - 1]):
swap( A, k, k - 1)
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
a=[10,2,13,44,5]
bubblesort(a)
Appendix-B Solved Programs in Python App-B .11

for i in range( len( a ) ):


print (a[i])
Sample Input/Output:
2
5
10
13
44

22. Write a program to perform matrixaddition


A = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
B = [[1,1,1],
[2,2,2],
[3,3,3]]
C = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
C[i][j] = A[i][j] + B[i][j]
for i in C:
print(i)
Sample Input/Output:
[2,3,4]
[6,7,8]
[10,11,12]

23. Find the transpose of a given matrix


The transpose of a matrix is a new matrix whose rows are the columns of the original.
T
5 4 3 5 4 7
4 0 4 4 0 10
   
7 10 3  
  3 4 3
A = [[12,7], [4 ,5], [3 ,8]]
transpose = [[0,0,0], [0,0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
transpose[j][i] = A[i][j]
for i in transpose:
print(i)

Sample Input/Output:
[12,4,3]
[7,5,8]

24. Write a program that returns the position of the largest element in anarray
from array import *
myArray = array(‘i’, [10,2,13,44,5])
maxi=myArray[0]
pos=0
for i in range(len(myArray)):
if(myArray[i]>maxi):
maxi=myArray[i]
pos=i
print(“Maximum”,maxi,”at position”,pos+1)

Sample Input/Output:
Maximum 44 at position 4

25. Write a program to count the number of positive integers in a collection of


numbers.
from array import *
myArray = array(‘i’, [-10,2,-13,-44,5])
cnt=0
for i in range(len(myArray)):
if(myArray[i]>0):
cnt=cnt+1
print(“Number of positive integers:”,cnt)

Sample Input/Output:
Number of positive integers: 2

STRINGS
26. Read a string and find the number of vowels present in thestring
s=input(‘Enter a string:’)
cnt = 0
for i in range(len(s)):
if s[i]==’a’ or s[i]==’e’ or s[i]==’i’ or s[i]==’o’ or s[i]==’u’:
cnt=cnt+1
print (“Number of vowels:”,cnt)

Sample Input/Output:
Enter a string: apple
Number of vowels:2

27. Readastringandcountthenumberofoccurrencesofagivencharacterinthe string


s=input(‘Enter a string:’)
ch=input(‘Enter a character:’)
cnt = 0
for i in range(len(s)):
if s[i]==ch:
cnt=cnt+1
print (“Number of occurerences:”,cnt)

Sample Input/Output:
Enter a string: apple
Enter a character: p
Number of occurrences: 2
App-B.14 Problem Solving and Python Programming

28. Read a string and count the number of words in thestring


s=input(‘Enter a string:’)
cnt = 0
for i in range(len(s)):
if s[i]==’ ‘:
cnt=cnt+1
print (“Number of words:”,cnt+1)

Sample Input/Output:
Enter a string: This is an example
Number of words: 4

29. Read a string and display in reverseorder


s=input(‘Enter a string:’)
i=len(s)-1
rev=’’
while(i>=0):
rev=rev+s[i]
i=i-1
print (“Reverse:”,rev)

Sample Input/Output:
Enter a string: example
Reverse: elpmaxe

30. Define a function that can accept two strings as input and print the string
withmaximumlengthinconsole.Iftwostringshavethesamelength,thenthe
function should print al l strings line byline.
def printValue(s1,s2):
len1 = len(s1)
len2 = len(s2)
if len1>len2:
print s1
elif len2>len1:
print s2
Appendix-B Solved Programs in Python App-B .15

else:
print s1
print s2

s1=raw_input()
s2=raw_input()
printValue(s1,s2)
Sample Input/Output:
Python
Example
Example

FUNCTIONS
31. Write a function to check whether a given number is even orodd
def check(no):
if (no%2)==0:
print (“Even”)
else:
print (“Odd”)
no=int(input(‘Enter a number’))
check(no)

Sample Input/Output:
Enter number: 4
Even

32. Write a function to check whether a given number is perfect ornot


def isPerfect(no):
sum=0
for i in range(1,no):
if no%i==0:
sum=sum+i
return sum
no=int(input(‘Enter a number’))
App-B.16 Problem Solving and Python Programming

if no==isPerfect(no):
print(“Perfect number”)
else:
print(“Not a Perfect number”)

Sample Input/Output:
Enter a number 28
Perfect number

33. Write a function to find the reverse of a givennumber


def reverse(no):
rev=0
while no>0:
rem=no%10;
rev=rev*10+rem
no=no//10
return rev
no=int(input(‘Enter a number’))
print (“Reverse :”,reverse(no))

Sample Input/Output:
Enter a number 123
Reverse: 321

34. Write a function to check whether a given number is a palindrome ornot


def reverse(no):
rev=0
while no>0:
rem=no%10;
rev=rev*10+rem
no=no//10
return rev
no=int(input(‘Enter a number’))
if reverse(no)==no:
Appendix-B Solved Programs in Python App-B .17

print (“Palindrome”)
else:
print(“Not a Palindrome”)

Sample Input/Output:
Enter a number 121
Palindrome

35. WriteafunctiontocheckwhetheragivennumberisanArmstrongnumber ornot


def check(no):
sum=0
while no>0:
rem=no%10
sum=sum+rem*rem*rem
no=no//10
return sum
no=int(input(‘Enter a number’))
if no==check(no):
print (“Armstrong Number”)
else:
print(“Not a Armstrong Number”)

Sample Input/Output:
Enter a number 153
Armstrong number

36. Writeafunctiontofindthesumofindividualdigitsinagivenpositiveinteger
number
def sumofdigits(no):
sum=0
while no>0:
rem=no%10
sum=sum+rem
no=no//10
App-B.18 Problem Solving and Python Programming

return sum
no=int(input(‘Enter a number’))
print (“Sum of digits:”,sumofdigits(no))

Sample Input/Output:
Enter a number 123
Sum of digits: 6

LISTS, TUPLES AND DICTIONARIES


37. Write a program to compute sum and multiplies all the items in alist
def sum_multiply_list(items):
tot = 1
sum=0
for x in items:
tot *= x
sum+=x
print(“sum:”,sum)
print(“Multiplies:”,tot)
sum_multiply_list([11,2,-8])

Sample Input/Output:
Sum: 5
Multiplies: -176

38. Write a program to get the smallest and largest number from alist
def smallest_large_list( list ):
min = list[ 0 ]
max=list[0]
for a in list:
if a <min:
min = a
elif a>max:
max=a
print(“Max:”,max,”Min:”,min)
Appendix-B Solved Programs in Python App-B .19

smallest_large_list([1, 2, -8, 0])

Sample Input/Output:
Max:2 Min:-8

39. Write a program to remove duplicates from alist.


a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)

Sample Input/Output:
{40, 10, 80,50,20,60,30}

40. Writeaprogramtocountnumberofelementsinthelistwithinaspecified
range
def count_range_in_list(li, min, max):
ctr = 0
for x in li:
if min <= x <= max:
ctr += 1
return ctr
list1 = [10,20,30,40,40,40,70,80,99]
print(count_range_in_list(list1, 40, 100))
list2 = [‘a’,’b’,’c’,’d’,’e’,’f’]
print(count_range_in_list(list2, ‘a’, ‘e’))

Sample Input/Output:
6
5
App-B.20 Problem Solving and Python Programming

41. Write a program to clone or copy alist


original_list = [11, 22, 44, 23, 54]
new_list = list(original_list)
print(original_list)
print(new_list)

Sample Input/Output:
[11, 22, 44, 23, 54]
[11, 22, 44, 23, 54]

42. Write a program to reverse atuple


x = (“example”)
y = reversed(x)
print(tuple(y))
x = (5, 10, 15, 20)
y = reversed(x)
print(tuple(y))

Sample Input/Output:
(‘e’,’l’,’p’,’m’,’a’,’x’,’e’)
(20, 15, 10, 5)

43. With a given integral number n, write a program to generate a dictionary


that contains (i, i*i) such that is an integral number between 1 and n (both
included).
n=int(raw_input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print d

Sample Input/Output:
4
{1:1, 2:4, 3:9, 4:16}
Appendix-B Solved Programs in Python App-B .21

44. Write a program that accepts sequence of lines as input and capitalize each
character.
lines = []
while True:
s = raw_input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print sentence

Sample Input/Output:
Example
EXAMPLE

45. Write a program that accepts a sentence and calculate the number of letters
anddigits.
s = raw_input()
d={“digits”:0, “letters”:0}
for c in s:
if c.isdigit():
d[“digits”]+=1
elif c.isalpha():
d[“letters”]+=1
else:
pass
print “LETTERS”, d[“letters”]
print “DIGITS”, d[“digits”]

Sample Input/Output:
Hello world 123
LETTERS 10
DIGITS 3
App-B.22 Problem Solving and Python Programming

46. Write a program that accepts a sentence and calculate the number of upper
case letters and lower caseletters.
s = raw_input()
d={“upper case”:0, “lower case”:0}
for c in s:
if c.isupper():
d[“upper case”]+=1
elif c.islower():
d[“lower case”]+=1
else:
pass
print “upper case”, d[“upper case”]
print “lower case”, d[“lower case”]

Sample Input/Output:
Hello
upper case 1
lower case 4

47. Defineafunctionwhichcanprintadictionarywherethekeysarenumbers
between 1 and 3 (both included) and the values are square of keys
def printDict():
d=dict()
d[1]=1
d[2]=2**2
d[3]=3**2
print d
printDict()

Sample Input/Output:
{1:1, 2:4, 3:9}

48. Withagiventuple(1,2,3,4,5,6,7,8,9,10),writeaprogramtoprintthefirsthalf
values in one line and the last half values in other line
tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
tp2=tp[5:]
Appendix-B Solved Programs in Python App-B .23

print tp1
print tp2
File, Errors

Sample Input/Output:
{1,2,3,4,5}
{6,7,8,9,10}

49. Write a function to compute 5/0 and use try/except to catch theexceptions.
def throws():
return 5/0
try:
throws()
except ZeroDivisionError:
print “Divide by zero!”
except Exception, err:
print ‘Caught an exception’
finally:
print ‘In finally block for cleanup’

Sample Input/Output:
Divide by zero !
In finally block for cleanup

50. WriteaprogramthathandlesIndexError,whichcouldoccuriftheindexpro- vided


exceeds the length of the list.
def print_list_element(thelist, index):
try:
print(thelist[index])
except IndexError:
print(“The list has no element at index %d.” % index)
l=[1,2,3,4]
print_list_element(l,4)

Sample Input/Output:
The list has no element at index 4.
App-B.24 Problem Solving and Python Programming

51. Write a program to read a random line from afile


import random
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(random_line(‘test.txt’))

Sample Input/Output:
File random access

52. Rewrite the previous program so that the exception which is caught in the
except clause is re-raised after the error message isprinted.
def print_list_element(thelist, index):
try:
print(thelist[index])
except IndexError as ie:
print(“The list has no element at index %d.” % index)
raise ie
l=[1,2,3,4]
print_list_element(l,4)

Sample Input/Output:
The list has no element at index 4
Traceback (most recent call last):
File “main.py”, line 8, in <module>
print_list_element(l,4)
File “main.py”, line 6, in print_list_element
raise ie
IndexError: list index out of range
UNVERSITY QUESTION PAPERS

Question paper code: 25109


B.E./B.Tech. Degree Examination, December/January 2019.
First Semester
Civil Engineering
GE 8151 –Problem Solving and Python Programming
(Regulations 2017)
Time:Three hours Maximum: 100marks

Answer ALL Questions.

PART A – (10×2=20 marks)

1. Distinguish between algorithm andprogram.


2. Write an algorithm to find the minimum number in a given list ofnumbers.
3. What are keywords? Giveexamples.
4. State the reasons to divide programs intofunctions.
5. Present the flow of execution for a whilestatement.
6. Define recursion with anexample.
7. Relate strings andlists.
8. Give a function that can take a value and return the first key mapping to that value in a
dictionary.
9. What is a module? Giveexample.
10. Find the syntax error in the code given:

While True print (“Helloworld”)

PART B – (5×16=80 marks)


11. (a) (i) Discuss about the building blocksof algorithms. (8)
(ii) Write a recursive algorithm to solve towers ofHanoiproblem. (8)
Or
(b) (i) Identify the simple strategies for developingandalgorithm. (8)
(ii) Write an algorithm to insert a card into a list ofsortedcards. (8)
12. (a) (i) Sketch the structures of interpreter and compiler. Detail the differences between them.
Explain how python works in interactive mode and script mode with examples.(2+2+4)
(ii) Summarize the precedence of mathematical operatorsinpython. (8)
UQP.2 Problem Solving and Python Programming
Or
(b)(i)ExplainthesyntaxandstructureofuserdefinedfunctionsinPythonwithexamples. Also discuss
about parameter passinginfunctions (12)
(ii) Write a Python function to swap the values oftwovariables. (4)
13. (a) (i) List the three types of conditional statements andexplain them. (16)
Or
(b) (i) Python strings are immutable, Justify withan example. (8)
(ii)WriteaPythoncodetoperformbinarysearch.Traceitwithanexampleofyour choice. (8)
14. (a) (i) Discuss the different options to traversealist. (8)
(ii) Demonstrate the working of +, * and slice operatorsin python. (8)
Or
(b) (i) Compare and contrast tuples and listsinPython. (4)
(ii) Write a script in Python to sort n numbers usingselectionsort. (12)
15. (a) (i) Explain the commands used to read and write into a filewithexamples. (8)
(ii) Discuss about the use of format operator infileprocessing. (8)
Or
(b) Describe how exceptions are handled in Python withnecessaryexamples. (16)
Previous Year UniversityQuestionPapers UQP.3
Question paper code: 54009
B.E./B.Tech. Degree Examination, January 2018.
First Semester
Civil Engineering
GE 8151 –Problem Solving and Python Programming
(Regulations 2017)
Time:Three hours Maximum: 100marks

Answer ALL Questions.

PART A – (10×2=20 marks)

1. What is analgorithm?
2. Write an algorithm to accept two numbers, compute the sum and print theresult.
3. Name the four types of scalar objects Pythonhas.
4. What is a tuple? How literals of types tuples are written? Givenexamples?
5. Write a Python program to accept two numbers, multiply them and print theresult.
6. Write a Python program to accept two numbers, find the greatest and print theresult.
7. What is a list? How lists differ fromtuples?
8. How to slice a list inPython?
9. Write a Python script to display the current date andtime?
10. Write a note on modulardesign.

PART B – (5×16=80 marks)


11. (a) (i) Draw a flow chart to accept three distinct numbers, find the greatest and print the
result. (8)
(ii) Draw a flow chart to find the sum ofseries 1+2+3+4+5+…+100. (8)
OR
(b) (i) Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi
problem withrelevantdiagrams (16)
12. (a) (i) What is a numeric literal?Give examples. (4)
(ii) Appraise the arithmetic operators in Pythonwith example. (12)
Or
(b) (i) Outline the operator precedence of arithmetic operatorsin Python. (6)
(ii) Write a Pyton program to exchange the value oftwo variables. (4)
UQP.4 Problem Solving and Python Programming
(iii) Write a Python program using function to find thesum of first „n‟ even numbersand
printtheresult. (6)
13. (a) (i) Appraise with an example nested if and elif headerin Python. (6)
(ii)Explainwithanexample while loop, break statement and continue statement inPython.
(10)
Or
(b)(i)WriteaPythonprogramtofindthefactorialofagivennumberwithoutrecursionand with
recursion andwith recursion. (8)
(ii) Write a Python program to generate first „N”Fibonaccinumbers. (8)
14. (a) (i) What is a dictionary in Python?Givenexample. (4)
(ii) Appraise the operations for dynamicallymanipulating dictionaries. (12)
Or
(b) (i) Write a Python program to perform linear search ona list. (8)
(ii)WriteaPythonprogramtostore„n‟numbersinalistandsortthelist using selection sort. (8)
15. (a) Tabulate the different modes for opening a file and explainthe same. (16)
Or
(b) (i) Appraise the use of try block and expect block in Pythonwith syntax. (6)
(ii) Explain with an examples exceptions with argumentsinPython. (10)

You might also like