Unit Ii Part B
Unit Ii Part B
in/
GE8151 PROBLEM SOLVING AND PYTHON
PROGRAMMING
UNIT – II
Problem Solving and Python Programming
DATA, EXPRESSIONS, STATEMENTS
/
.in
PART-B
INTRODUCTION TO PYTHON;
an
- Python is a general purpose programming language created by Guido Van Rossum during
a
1985 – 1990 at Netherlands.
iy
- Python got its name from a BBC comedy series named “Monty Python’s Flying Circus”.
or
- It is an Interpreted, Interactive, object Oriented, High level programming language.
.p
FEATURES OF PYTHON PROGRAMMING;
w
→ Python is interpreted
w
→ Python is Interactive
s:
tp
Objects.
→ Python is Extensible
→ Python is Portable
PYTHON INTERPRETER;
/
in
- Python is considered an Interpreted language because python programs are executed by
n.
an
aa
Interpreter.
iy
or
.p
- Interpreter takes single instruction as input.
w
- It executes one line at a time.
w
COMPILER;
- It is a program used to convert a high level language into a low level language.
/
in
(ii) Script Mode.
n.
(i) Interactive Mode:
aa
- It allows us to write codes in python command prompt.
riy
- The chevron (>>>) is the prompt the interpreter use to indicate that it is ready to accept
instruction.
o
.p
- So that the Interpreter with >>> prompt indicates it is in Interactive mode.
w
- In this mode python code can be typed directly and results will be displayed immediately.
w
- Drawback: We cannot sare the statements for further use. We have to retype all the
s:
- Example:
ht
>>> 5 + 10
15
>>> 5 + 50 * 10
505
Python programming
>>> x = 10
>>> y = 15
>>> z = x + y
Sum = 25
/
in
- Script is a text file containing the python statements.
n.
- In this mode python program is typed in a file and then using interpreter it will be
executed to get the output.
aa
- Python Scripts must be sared with py extension before execution.
- Once python Scripts are sared it can be used again and again for execution without
iy
re typing.
or
- Python Scripts can be edited. .p
- Example:
w
Print ( “ My First Program”)
w
x = 10
//w
y = 20
z = x+y
Print ( “ Sum of two Numbers = “, z )
s:
tp
Output:
ht
My First Program
VALUES;
DATATYPES IN PYTHON;
/
in
n.
aa
riy
(i) Numbers;
o
-
.p
Number data type stress Numerical values.
- It is immutable (i.e.) values cannot be changed.
w
- Numbers are again classified into the following types:
w
Ex; 3 + 2j
(ii) Boolean:
(iii) Sequence:
/
in
- Three types of sequence data types available in python. They are,
1. Strings - Collection of characters,
n.
Numbers and symbols.
aa
- represented by single or double Quotes.
- Example: “abc “, ‘python 3 ‘
riy
2. Tuple - Group of elements enclosed in parentheses. ()
• They are immutable (i.e.) values cannot be changed.
•
o
Example: x = ( 1, 2, 3, “ abc “ )
.p
3. List - Group of elements enclosed in square brackets [ ]
w
• They are Mutable (i.e.) values in a list can be changed
w
• Example: l1 = [ 1, 2, “ a “ , 1.5 ]
//w
(iv) Dictionary:
s:
- Dictionary is a data type that contains elements based on key: value pour.
tp
→ To find the type of data type () function can be used. It is a Built – in Library function.
→ Example: x = 10
y = “abc “
- In order to convert data from one type to another type Data type conversion is
needed.
- It can be done by using the type name as a function.
/
in
Function Description
n.
int ( x , base ) Converts x to an integer, base specifies the
aa
Base if x is a string.
float ( x ) Converts x to a floating point number.
iy
Complex ( real, image ) Creates a complex number.
or
Str ( x ) Converts x to a string.
Chr ( x ) .p Converts an integer to a character.
List ( x ) Converts x to a list.
tuple ( x ) Converts x to a tuple.
w
dict ( x ) Creates a dictionary, where x must be a
w
Example: 1 Example: 2
ht
5 + 2j
“2.5 “ [1, 2]
(1, 2)
{11: “Flower”, 22: “Fruit”}
KEYWORDS;
/
in
- Keywords cannot be used as Identifiers.
- In python 3 it has 33 keywords. They are as follows:
n.
and elf import raise False These
aa
as else in return None 3
assert except is try True keywords
iy
break finally lambda While starts
or
class for nonlocal With with
Continue from not yield capital
.p
def. global or letters.
w
del if pass
w
IDENTIFIERS;
- Identifier is the name given to identify variable, Function, Module, class etc. in
//w
python.
• It is Case – Sensitive (i.e.) Lower case and upper case letters are different.
• It should not be a keyword.
• It can be of any length.
Example:
Number 12 total
- abc
XYZ
VARIABLES:
/
- In python declaration of variable is not needed. We can simply assign a value to a
in
variable.
n.
- Values can be assigned using Assignment statement. It creates a new variable and
assigns them value.
aa
- Syntax:
Variable Name = value
riy
(Or)
Variable Name = Expression
- Example :
o
.p
A1 = 10
w
B1 = (5 * 20) + 10
w
Statement:
ht
Expression:
Example:
42
a+b
10 + 5 – 6
/
INPUT & OUTPUT STATEMENTS IN PYTHON;
in
Input Statement;
n.
- It is used to get input from user using keyboard.
aa
- Syntax :
Variable Name = input ()
iy
(Or)
or
Variable Name = input (“String “ )
Example :
-
.p
a = input () (or) a = input (“Enter a value “ )
w
- In python by default all the input values are considered as string. So if we want to get
w
values of different type, then input () statement must be written within type
conversion function.
//w
- Example :
s:
Method: 1 Method: 2
Output Statement:
/
Example: 2
in
x = 10
n.
y = 20
aa
z=x+y O/P:
iy
Print (“Sum = “, z ) Sum = 30
or
INDENTATION: .p
- To define a block of code python use Indentation.
w
- It can be a single tab space (or) four space (By pressing space bar).
- When a Block ends the next line of code must be unindented.
w
Example :
//w
a = 10 if (a > 20):
else:
tp
- It can be used within Function or class to explain what a Function or class will do.
- Triple Quotes (‘’’ - ‘’’ ) is the symbol used to represent it.
- Example : ‘’’ Program to Add two values
/
Created on: 06 – 06 -2019
in
Author: Geetha T. V ‘’’
n.
TUPLE ASSIGNMENT:
aa
- Python has a very powerful tuple assignment feature that allows a tuple of variables
on the left of an assignment to be assigned values from a tuple on the right of the
iy
assignment.
or
- Left side is a tuple of variables and Right side is a tuple of values.
- The Number of variables on the Left and Number of values on Right must be same
.p
- Each value is assigned to its respective variables.
w
- Tuple Assignment can be done by a process known as “Tuple Packing / Un packing
“. (i.e.) values in a tuple on right are unpacked into the variables on right.
w
- Example : 1
//w
Print (name)
tp
25 print (uid)
god
a given character.
OPERATOR IN PYTHON;
/
.in
(iii) Assignment Operators.
(iv) Logical Operators.
n
(v) Bitwise Operators.
aa
(vi) Membership Operators.
(vii) Identity Operators.
iy
(i) Arithmetic Operators:
or
- They are used to perform basic arithmetic operations. Such as Addition, subtraction,
.p
Multiplication and Division.
w
Operator Description Example
a = 10, b = 3
w
Division
ht
- These operators are used to compare the values to find the relation among them.
- It return Boolean value. (i.e) True / False.
Operator Description Example
a = 10, b = 3
== It checks two values are a = = b → False
Equal
!= It checks two values are a! = b → True.
Not Equal
> It checks one value a > b → True
/
in
greater than another
< It checks one value less a < b → False
n.
than another value.
aa
>= It checks one value a > = b → True
greater than or equal to
iy
another value.
It checks one value less
or
than or equal to another
.p
<= value. a < = b → False
w
w
- These operators are used to check two or more conditions at the same time.
s:
Truth Table:
Condition 1 Condition 2 and or
True True True True
True False False True
False True False True
False False False False
/
in
n.
Not
aa
Input Output
True False
iy
False True
Operator Description
//w
Example
a = 010, b = 011
and )
1
ht
/
in
n.
(v) Assignment Operator:
aa
- It is used to assign a value or an expression to another variable.
Operator Description Example
iy
= Assign values from right C = 12
side operand to Left side Z =x+y
or
variable.
.p
- It can be combined with all Arithmetic operators to form Arithmetic Assignment
w
Operator.
w
- Ex: y = 5 ; y + = 2 ; → y = y + 2 O/P: y = 7
/
in
Operator Description Example
x = 10, y = 10
n.
Is Returns True, if the x is y
aa
variables on both sides of ↓
the operator has same value True
iy
otherwise False.
or
is not Returns True, if the x is not y
variables on both side of the
.p ↓
operator has different value False
otherwise return False.
w
w
//w
The following table list all operators from highest precedence to lowest with its associativity.
1. Evaluate sum = x – y / 3 + z * 3 – 1
/
in
Where x = 3, y = 9, z = 77
n.
Soln:
aa
Sum = x – y / 3 + z * 3 – 1
3 – 9 / 3 + 77 * 3 – 1
iy
or
3 – 3 + 77 * 3 – 1
3 – 3 + 231 -1
.p
0 + 231 – 1
w
231 – 1
w
//w
230
Ans: Sum = 230
s:
2. Evaluate: (3 – 9) / 3 + 77 * (3 – 1)
tp
Soln:
ht
(3 – 9) / 3 + 77 * (3 – 1)
- 6 / 3 + 77 * (3 – 1)
- 6 / 3 + 77 * 2
- 2 + 77 * 2
- 2 + 154
152
Ans = 152
d=a<b>c–1
= 2 < 12 > 1 – 1
2 < 12 > 0
/
in
1>0
n.
1
aa
Ans: d = 1
iy
4. Evaluate: 2 * * 3 + 4 // 7 – 6 * 9
or
Soln:
2 * * 3 + 4 // 7 – 6 * 9
.p
w
8 + 4 // 7 – 6 * 9
w
8+0-6*9
//w
8 + 0 - 54
8 - 54
s:
- 46
tp
Ans = - 46
ht
FUNCTION IN PYTHON;
Definition:
- Functions are set of related statements that will perform a specific task.
- If helps us to break the program into small units or modules.
- So it is called as Modular programming.
- Debugging, Testing and maintenance becomes eary when the program is divided
into subprograms.
- Functions can make a program smaller by eliminating repetitive code.
- Functions provide code re – usability.
- The length of the program is reduced.
- Testing small parts of the program can be done separately.
Types of Functions:
/
in
(ii) User – defined Function.
n.
(i) Built – in – Function:
aa
- They are already created by the develop and stored in system Libraries.
- We can able to use them but we cannot able to modify them.
iy
- Examples:
or
• max () – returns the largest element
• len () - returns the length of a string
.p
• sqrt () - returns the square root of a Number.
w
• Print () – used to display a value.
w
- Function components :
tp
(a) Function Header: It must begin with the keyword “def. “followed by Function
Name and parenthesis () and ends with colon (: ). Inside parenthesis parameters can
be use.
(b) Function Body: It’s with indentation and ends with an optional return
statement.
- Syntax :
/
in
Flow of Execution:
n.
- It means the order in which statements are executed.
aa
- Function starts its execution when it is called.
- When a function is called, python Interpreter will check the Name and No. of
iy
arguments present in Function call is same as in Function Definitions.
or
- If they are same the Function Definition Start to execute.
- Execution always begin at the first statement of the program.
.p
- Statements are executed one at a time in order from top to bottom.
w
- When the end of Function definition is reached then the next line of the Function call
w
will be executed.
//w
Example:
s:
tp
ht
Output:
Sum = 9
Difference = 7
Explanation:
In the above program two Functions named as Add and sub are defined. When
Add(2,3,4) is called its corresponding Definition will get executed and after its completion the
second function call sub(10,3) will gets called and its definition will get executed, by
assigning value of 10 and 3 to x and y.
Parameters:
/
in
- Parameters are the values provided in function header.
n.
- These are the values required by function to work.
- It is also called as Formal parameters.
aa
- Example: def. Add ( a , b ) :
↓
iy
a, b → Parameters.
or
Arguments: .p
- Arguments are the values provided in function call.
w
- List of arguments should be in same number and type of arguments as present in
w
function header.
- It is also called as Actual Arguments.
w
↓
s:
TYPES OF ARGUMENTS;
- Values passed in Function call are called arguments. They can be of the
following types.
(i) Required arguments
(ii) Keyword arguments
(iii) Default arguments
(iv) Variable length arguments.
/
in
Print (“Age: “, age ) Age: 18
Example (“Anju “, 18 )
n.
(ii) Keyword arguments:
aa
- In function call if the arguments are not in positional order using keywords they can
iy
be matched with the corresponding values.
or
Example
def. Example (name, age): .p O/P:
Print (“Name: “, name ) Name: Anju
w
Print (“Age: “, age ) Age: 18
Example (age = 18, name = “Anju )
w
- In function call if proper values are not given then default values will be taken.
s:
/
in
- It can be done by two ways.
n.
(i) Pass By value (ii) Pass By Reference
aa
- In this method actual - In this method changes done in formal
Value is passed. argument will reflect in actual
iy
- Changes done in formal argument.
argument will not reflect in - In python if the parameter belongs to
or
actual argument. .p list, dictionary it works by reference
- In python if the parameter belongs method.
to integer, string it works by this
w
Method.
w
Example: Example:
//w
Python will follow a method for parameter passing method called as call by object
(or) call by object Reference (or) call by sharing. Based on the data type the working will be
of pass by value or Reference.
MODULES;
/
in
- To access one of the function from a module dot ( ∙ ) notation should be used.
n.
- Syntax :
import Module Name ≠ To import a Module.
aa
Module Name. Function Name (arguments)
To access a function from a Module. It is called as Dot Notation.
iy
- Modules can be of two types.
or
(i) Built – in Module
(ii) User – defined Module.
.p
(i) Built – in Module ;
w
w
- We can access all the function from them but we cannot able to modify it.
- Example: Standard Library in python.
s:
(a) math :
ht
(b) random:
/
(ii) User – defined Module:
in
n.
- Module created by user according to their need.
- Steps to create a Module :
aa
1. Create a python file by including one or more functions and save it with py
extension.
riy
2. Include import statement.
3. Access the function inside module using dot Notation.
- Example :
o
.p
new. Py
w
w
def Add ( a , b ) :
//w
Print ( “ Sum = “ , a + b )
def Sub ( a , b ) :
Print ( “ Diff = “ , a – b )
s:
def Mul ( a , b ) :
tp
print ( “ Product = “ , a * b )
ht
Main. Py
import new
new. Add ( 2 , 3 )
new. Sub ( 15, 5 )
new. Mul ( 10 , 5 )
O/P: Sum = 5
Diff = 10
Product = 50
Explanation:
In the above program python file named as “new. Py “is created with three functions
named as Add, Sub, Mul.
Again in another python File the module “new “is imported and its function are
accessed. To get the output execute “main. Py “first.
/
Different ways to import a Module:
in
n.
1. Using import:
aa
- It is the simple and common way to import module.
- Example : import math
riy
Print (“value of pi = “, math. Pi)
O/P: value of pi = 3.14159
Print (“value of pi = “, pi )
O/P: value of pi = 3.14159
4. Using import *:
/
in
- Example :
• Sum = lambda ( a, b, c ) : a + b + c
n.
Print (“Answer = “, sum (10, 20, 30) )
aa
O/P: Answer = 60
• area = lambda ( l , b ) : I * b
riy
Print (“Area of Rectangle = “, area (5, 15) )
O/P:
Area of Rectangle = 75
o
.p
LIPETIME AND SCOPE OF A VARIABLE;
w
Lifetime:
w
//w
Scope:
ht
2. Global Variable
Example:
a = 20 ≠ Global Variable
a = 30 ≠ Local variable.
/
in
Display ()
n.
Print (“Value outside Function “, a )
aa
O/P:
riy
Value inside Function 30
o
→ Local variable can be accessed like
.p
w
Global variable using “global “keyword.
w
Example:
//w
a = 20 ≠ Global variable
global a
tp
a = 30
ht
Display ()
O/P:
Inside Function: 30
ILLUSTRATIVE PROGRAMS;
/
in
b = int (input ())
n.
t=a
aa
a=b
riy
b=t
o
Output:
.p
w
Enter value 1
w
50
//w
Enter value 2
80
s:
Swapped values 80 50
tp
a, b = b, a
Output:
Enter value 1
5
Enter value 2
10
Swapped value: 10 5
/
in
2. Circulate the values of ‘n’ variables
n.
def Circulate (a, n):
aa
x = a [n:] + a [: n]
riy
Print [“Circulated List: “, x ]
o
Circulate (a, 2) ≠ clockwise Rotation
.p
w
Circulate (a, - 1) ≠ Anticlockwise Rotation
w
Output:
//w
Explanation:
tp
1 2 3 → Index position
ht
Using ‘+ ‘operator a [2:] + a [: 2] both List a are concatenated to produce the result
x = [30, 40, 10, 20]
x = a [ -1 : ] + a [ : -1 ] ≠ a [ -1 : ] → [ 40 ] from the
/
.in
≠ a [: -1] → [10, 20, 30] from position 0 to -2 the
n
element are sliced from List a.
aa
(i.e.) End value -1 , [ -1 -1 = - 2 ]
iy
Finally concatenating a [ -1 : ] + a [ : -1 ] the result will be [ 40, 10 , 20, 30 ]
or
3. Distance between two points:
.p
Formula: d = √(𝑥2 − 𝑥1 )2 + (𝑦2 − 𝑦1 ) 2
w
Import math
w
d = math. Sqrt (( x2 – x1 ) * * 2 + ( y2 – y1 ) * * 2)
Enter value of x2
3
Enter value of y1
Enter value of y2
/
in
2
n.
Distance between two points = 7.81024
aa
o riy
.p
w
w
//w
s:
tp
ht
Problem Solving and Python Programming (GE3151) – Reg 2021
Unit I: Computational Thinking and Problem Solving
Computational Thinking and Problem Solving | Fundamentals of Computing | Identification of Computational Problems |
Algorithms | Building Blocks | Notation | Algorithmic Problem Solving | Simple Strategies for Developing Algorithms |
Illustrative Problems | Anna University Two Marks Questions & Answers | Multiple Choice Questions and Answers
https://www.poriyaan.in/