0% found this document useful (0 votes)
19 views35 pages

Unit Ii Part B

PROBLEM SOLVING WITH PYTHON
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views35 pages

Unit Ii Part B

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

https://www.poriyaan.in/ https://eee.poriyaan.

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 processed at run time by the


//w

Interpreter. No compilation is needed

→ Python is Interactive
s:
tp

Using python prompt python programs can be executed directly.

→ Python is Object Oriented


ht

It Supports object oriented style of programming that encapsulates lodes within

Objects.

→ Python is Extensible

Python can be embedded with C, C++, Java Script etc.

→ Python is a Beginner’s Language

→ Python is Portable

Python programs can be executed on various platforms without altering them.

→ Python is Free and Open Source.


Python software can be downloaded and used freely.

→ Python has rich set of Built – in standard Libraries.

→ Python is simple, easy to learn and maintain.

PYTHON INTERPRETER;

/
in
- Python is considered an Interpreted language because python programs are executed by

n.
an

aa
Interpreter.

- An Interpreter reads a high level program and executes it.

iy
or
.p
- Interpreter takes single instruction as input.
w
- It executes one line at a time.
w

- No Intermediate object code is generates.


//w

- Errors are displayed for every instruction.


s:

- It requires less amount of Memory.


tp

- Example: Python, JAVA.


ht

COMPILER;

- It is a program used to convert a high level language into a low level language.

- It takes entire program as input.

- Intermediate object code is generated.

- Errors are displayed after entire program is checked.

- It requires more memory since object code is generated.


https://eee.poriyaan.in/
- Example: C, C++

MODES OF PYTHON INTERPRETER;

Python Interpreter can be used in two different ways. They are,

(i) Interactive Mode

/
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

- This mode is use full to test small pieces of code.


//w

- It can also be used as a calculator.

- Drawback: We cannot sare the statements for further use. We have to retype all the
s:

Statements to re – run them.


tp

- Example:
ht

>>> 5 + 10

15

>>> 5 + 50 * 10

505

>>> print (“Python programming”)

Python programming

>>> x = 10

>>> y = 15
>>> z = x + y

>>> print (“Sum = “, z)

Sum = 25

(ii) Script Mode:

/
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

Sum of two Numbers = 30

VALUES AND TYPES;

VALUES;

- Value can be any data represented by Number, letter or string.


- Example: 2, 42.5, ‘a’, “Hello”.
- These values belongs to different data types.

DATATYPES IN PYTHON;

- Data types are used to classify one particular type of data.


- This is important because the specific data type will determine what values can be
assign in it and what operations can be perform on it.

/
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

1. Integer - They are positive or negative whole numbers with no


decimal
//w

Point. Ex: 56, 125


2. Float - They are written with a decimal point dividing the
integer and
the fractional part.
s:

Ex: 5.63, 0.75


tp

3. Complex - They are of the form a + bj


ht

Where ‘a’ is the real part and

and ‘b’ is the imaginary part.

Ex; 3 + 2j

(ii) Boolean:

- Boolean is a data type having two values denoted by true or False.


- It is the value returned by conditional statements.
- The internal value of true is 1 and false is 0.
- Example: >>> True + 1
2
>>> False + 1
https://eee.poriyaan.in/
1

(iii) Sequence:

- A sequence is an ordered collection of data.


- It is a combination of mutable and immutable data types.

/
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

- All elements in dictionary are enclosed within curly brackets { }.


- In Dictionary keys are immutable and values are mutable.
ht

- Example : 𝑑1 = { 1 ∶ "flowers" , 2 ∶ "fruit " }

→ To find the type of data type () function can be used. It is a Built – in Library function.

→ Example: x = 10

y = “abc “

z = [1, 2, “a “, 3.5] o/p:

Print (type (x)) < Class ‘int’ >

Print (type (y)) < Class ‘Str’>

Print (type (z)) < Class ‘list’>


DATA TYPE CONVERSION;

- 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

sequence of ( key : value ) tuples / List


//w

hex ( x ) Converts an integer to hexadecimal.


Oct ( x ) Converts an integer to an octal.
s:
tp

Example: 1 Example: 2
ht

>>> int (12, 25) X = {1: “Sun “, 2: “Moon “ }

12 print (list (x))

>>> Float (35) print (tuple (x))

35.0 Y = [[11, “Flower”], [22, “Fruit”]]

>>> Complex (5, 2) Print (dict (y))

5 + 2j

>>> Str (2.5) o/p:

“2.5 “ [1, 2]

(1, 2)
{11: “Flower”, 22: “Fruit”}

KEYWORDS;

- Keywords are the reserved words in python.


- They have special meaning and cannot be used for any other purpose.

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

- Rules for Naming Identifier:


s:

• An Identifier must start with an alphabet or underscore


tp

• It should not start with numbers.


ht

• 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:

Valid Identifier Inralid Identifier

Sum 5 Name ≠ starts with Number

reg – name Stud Name ≠ space is n

Number 12 total
- abc

XYZ
VARIABLES:

- A variable is a name that refers to a value.


- When a variable is created it will allocate some memory space to store values in
memory.

/
- 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

- Single value can be assigned to several variables.


Ex: a = b = c = 15
//w

- Multiple values can be assigned to multiple variables.


Ex: name, regno, Addr = “Geetha “, 8, “Ngl “
s:

STATEMENT AND EXPRESSION;


tp

Statement:
ht

- Instructions that a python Interpreter can execute are called statements.


- A statement is a unit of code like creating a variable a displaying a value.
- Example :
n = 17 ≠ Assignment Statement
Print (“Good Morning “ ) ≠ print statement.

Expression:

- An Expression is a combination of values, variables and operators.


- A value all by itself is considered an expression and also a variable,

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:

(i) X = input () ≠ accept string


tp

(ii) X = int (input ()) ≠ accept Integer


ht

(iii) X = float (input ()) ≠ accept Float

Ex: print (“Enter Name “ )

Name = input () name = input (“Enter Name’

Print (“Enter Reg No “ ) reg = int (input (“Enter Reg No”))

regno = int (input ())

Method: 1 Method: 2

Output Statement:

- If 1’s used to display the output value on screen.


- Function used is print ().
- Syntax :
Print (value / Expression / variable)
- Example : 1 O/P:
Print (“Hello “ ) Hello

/
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):

Print (“A is Bigger than 20 “ )


s:

else:
tp

Print (“A is smaller than 20 “ )


ht

COMMENT STATEMENT IN PYTHON;

- Comment statements are used to add additional information about a program or a


statement to explain it in Natural language.
- It starts with a hash sign (≠).
- With this user can able to understand what the code does? and why the code is
used?
- It has no effect on the execution of the program. (i.e.) when python Interpreter see ≠
it ignores all the text after ≠ till the end of that line.
- ≠ is known as single line comment.
Example:
ans = l * b ≠ Calculate area of Rectangle.
Multiline Comment (or) Doc String:

- 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

T1 = (“Anu “, 25, 25000 ) ≠ Tuple packing


(name, age, salary) = t1 ≠ Tuple Un packing
s:

Print (name)
tp

Print (age) Example: 2 [To split Email Ii


Print (Salary) mailied = “god @ abc. Org “
ht

O/P: Anu (uid, domain) = mailed – split

25 print (uid)

25000 print (domain) O/P:

god

Split () – Splits a string with abc. Org

a given character.

OPERATOR IN PYTHON;

- Operators are symbols used to perform operations on operands.


- Operands are variable or values to which operation must be performed.
- Example: a + b Where a, b → Operands
+ → Operator.
- The following types of operators are supported by python.
(i) Arithmetic Operators.
(ii) Comparison Operators.

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

+ Used to Add values a + b = 13


//w

- Used to Subtract values a - b = -7


* Used to Multiply Values a * b = 30
s:

/ Used to Divide values a / b = 3.33


// Used to perform Quotient a // b = 3
tp

Division
ht

% Used to perform 𝑎%𝑏 = 1


Remainder Division
** Perform Exponential a ** b = 1000
Operation

(ii) Comparison / Relational Operators:

- 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

(iii) Logical Operators:


//w

- These operators are used to check two or more conditions at the same time.
s:

- It returns Boolean value.


tp

Operator Description Example


a = True, b = False
ht

And If all conditions are true it ( a and b )


returns True otherwise
False False
or If any one of the condition ( a or b )
is True it return True.
True
not If the input is True output not ( b ) → True
will be False and vice not ( a ) → False
versa.

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

(iv) Bitwise Operators:


or
.p
- These operators are used to perform operation on binary digits of a value.
w
- It perform bit – bit operation.
w

Operator Description
//w

Example
a = 010, b = 011

& Works on the principle of a & b = 010


s:

( Bitwise logical and.


tp

and )
1
ht

( Bitwise Works on the principle of a / b = 011


or ) logical or.
~ Works on the principle of ~ a = 101
( Bitwise logical not.
not )
It gives 1, when the input
( XoR ) values are different.
It gives 0, when the input
values are same.
<< Used to shift all the bits to a << 1 = 100
( Left Shift) Left side…….
>> a >> 1 = 001
( Right Shift ) Used to shift all the bits to
Right side.

/
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

- They are, +=, -=, *=, /=, % =, //=, **=


//w

- Ex: y = 5 ; y + = 2 ; → y = y + 2 O/P: y = 7

(vi) Membership Operators:


s:

- It is used to check a value is present in a sequence or not.


tp

- The sequence may be string, list or tuple.


ht

- It returns Boolean value.

Operator Description Example


x = 10, y = 10
In Returns True, if the value “ h “ in x
present in the sequence ↓
otherwise False. True
not in Returns True, if the value “ S “ not in x
not present in the ↓
sequence otherwise False. True.
(vii) Identity Operators:

- They are used to check the memory locations of two objects.


- It will check if two values are located on the some part of the memory.
- It returns Boolean value.

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

Operator Operator Name Associativity


s:

() Parentheses Left → Right


tp

** Exponentiation Right → Left


ht

*, /, //, % Multiply, Divide, Modulo Left → Right


+, - Addition, Subtraction Left → Right
<<, >> Left Shift, Right Shift Left → Right
& Bitwise and Left → Right
Bitwise xoR & or Left → Right
<,>,<=,>= Comparison Operator Left → Right
==,!= Equality Operator Left → Right
= , + = , - = , * = ,/ =, % = , Assignment Operator Right → Left
// =
is , is not Identity Operators Left → Right
in , not in Membership Operators Left → Right
not , and , or Logical Operators Left → Right
Examples:

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

3. If a = 2, b = 12 and c = 1, Evaluate the following expression: d = a < b > c – 1


Soln:

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.

Need for Function: / Use of Function

- 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:

(i) Built – in Function

/
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

• input () – get an input from user.


//w

(ii) User - defined Function:

- They are defined by the programmer according to their need.


s:

- Function components :
tp

(i) Function Definition:


- It defines the need of the function with the implemented logic. It contain two parts.
ht

(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 :

(ii) Function Call:


- When a function is defined it will execute only when it is called.
- A function can be called for number of times.
- Syntax ;

Function Name (arguments)

/
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 AND ARGUMENTS;

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

- Example : (i) Add (a, b )


//


s:

Actual arguments as variables.


tp

(ii) Add (10, 20)



ht

Actual arguments as values.

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.

(i) Required arguments:

- It must passed to a function in correct positional order.


- The number of arguments in the function call must match exactly with the
function definition.
- Example :
def. Example (name, age): O/P:
Print (“Name: “, name ) Name: Anju

/
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

(iii) Default arguments:


//w

- In function call if proper values are not given then default values will be taken.
s:

- Default values must be added in Function header.


- Example :
tp

def Example (name, age = 25): O/P:


ht

Print (“Name: “, name ) Name = Anu


Print (“Age: “, age ) Age = 25
Example (“Anu “ )

(iv) Variable Length argument:

- If the number of arguments passed to a function is not known in advance it can be


used.
- But we must use * asterisk before the parameter name.
- Example :
def Example (* name): O/P:
for i in name: Anu
Print (i) Python
Example (“Anu “ ) C
Example (“Python “, “C “, “C++” ) C++

PARAMETER PASSING METHODS;

- This method represent how values are passed to a function.

/
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

def swap (a, b): def change List (x):


s:

t=a x. append (5) ≠ Add c value to list


tp

a=b l1 = [100, 200, 300]


ht

b=t change List (l1)

Swap (10, 20) print (l1)

Print (a) O/P: 10

Print (b) 20 O/P: [100, 200, 300, 5]

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;

- A module is a file containing python definitions, functions, statements and classes.


- Group of functions will form a module.
- Standard Library in python is considered as modules.
- To use a module in our program it must be imported using “import “keyword.
- Once a module is imported into a program we can access all the functions and
variables of that module.
- Each module contain number of functions.

/
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

- Modules that are already created by the developer.


//w

- We can access all the function from them but we cannot able to modify it.
- Example: Standard Library in python.
s:

- Some of the modules from python Library.


tp

(a) math :
ht

- It contains lot of mathematical functions and contants.


- Ex:
→ Sqrt (x) - To find square root of x
→ Factorial (x) - To find factorial value x
→ Sin (x) - To find sin value of x.
→ Cos (x) - To find cos value of x.
→ Log (x) - To find log value of x.
→ Pi - To print value of pi

(b) random:

- It is used to generate random Numbers.


- Ex:
→ randint (a, b) - Generate random number between a and t
→ randrange (x) - Generate random number less than x.
→ random ( ) - It generates any random number.

/
(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

2. Using import with renaming:


o
.p
- Using this method module name can be renamed.
w
- Example: import math as m
w

Print (“Value of pi = “, m. pi)


//w

O/P: Value of pi = 3.14159

3. using from import:


s:
tp

- It is used to get specific code from a module.


- Example : from math import pi
ht

Print (“value of pi = “, pi )
O/P: value of pi = 3.14159

4. Using import *:

- It is used to import all function definitions from a module.


- Example : from math import *
Print (“value of pi = “, pi )
O/P: value of pi = 3.14159

ANONYMOUS FUNCTION; (or) LAMBDA FUNCTION

- Single line functions are called as Anonymous Function.


- It is otherwise called as Lambda Function.
- It contains a single expression as a body and not a block of statements.
- It does not have a return statement.
- It can have multiple argument but only one expression.
- Syntax:
Variable = lambda (arguments): expression

/
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

- It defines the liveliness of a variable present in memony.


- Liveliness of a variable inside a Function live as long as the function executes and it
destroyed when it returned from a function.
s:
tp

Scope:
ht

- It defines the portion of a program where the variable is recognized.


- Variable inside a function has Local scope and outside has Global scope.
- Two types of variables.
1. Local Variable
- They are defined inside a function.
- They are visible and available only within the function.

2. Global Variable

- They are defined outside a function


- It can be accessed and visible anywhere in the program

Example:
a = 20 ≠ Global Variable

def Display ():

a = 30 ≠ Local variable.

Print (“Value inside Function “, a )

/
in
Display ()

n.
Print (“Value outside Function “, a )

aa
O/P:

riy
Value inside Function 30

Value outside Function 20

o
→ Local variable can be accessed like
.p
w
Global variable using “global “keyword.
w

Example:
//w

a = 20 ≠ Global variable

def Display ():


s:

global a
tp

a = 30
ht

Print (“Inside Function: “, a )

Display ()

Print (“Outside Function: “, a )

O/P:

Inside Function: 30

Outside Function: 30 [Since variable a is declared as global]

ILLUSTRATIVE PROGRAMS;

1. Exchange the value of two variables


Method: 1 [Using temporary variable]

Print (“Enter value 1 “ )

a = int (input ())

Print (“Enter value 2 “ )

/
in
b = int (input ())

n.
t=a

aa
a=b

riy
b=t

Print (“Swapped values “, a, “/t”, b )

o
Output:
.p
w
Enter value 1
w

50
//w

Enter value 2

80
s:

Swapped values 80 50
tp

Method: 2 [Without using temporary variable]


ht

Print (“Enter value 1 “ )

a = int (input ())

Print (“Enter value 2 “ )

b = int (input ())

a, b = b, a

Print (“Swapped values: “, a, “/t”, b )

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 ]

a = [10, 20, 30, 40]

o
Circulate (a, 2) ≠ clockwise Rotation
.p
w
Circulate (a, - 1) ≠ Anticlockwise Rotation
w

Output:
//w

Circulated List: [30, 40, 10, 20]

Circulated List: [40, 10, 20, 30]


s:

Explanation:
tp

1 2 3 → Index position
ht

Consider, a = [10, 20, 30, 40]

-4 -3 -2 -1 → Negative Index position

During function call, circulate (a, 2),

x = a[2:] + a[:2] ≠ a [ 2 : ] → [ 30 , 40 ] will b

Sliced from List a.

≠ a [: 2] → [10, 20] will b

Sliced from List a.

Using ‘+ ‘operator a [2:] + a [: 2] both List a are concatenated to produce the result
x = [30, 40, 10, 20]

During function call, circulate (a, -1):

x = a [ -1 : ] + a [ : -1 ] ≠ a [ -1 : ] → [ 40 ] from the

Negative index position -1 the value is sliced from List a.

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

Print (“Enter value of x1: “ )


//w

x1 = int (input ())

Print (“Enter value of x2 “ )


s:

x2 = int (input ())


tp

Print (“Enter value of y1 “ )


ht

y1 = int (input ())

Print (“Enter value of y2 “ )

y2 = int (input ())

d = math. Sqrt (( x2 – x1 ) * * 2 + ( y2 – y1 ) * * 2)

Print (“Distance between two points = “, d )

Output: Enter value of x1

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

Unit II: Data Types, Expressions, Statements


Data Types, Expressions, Statements | Introduction to Python | How to Write and Execute Python Program | Concept
of Interpreter and Compiler | Python Interpreter | Interactive and Script Modes | Debugging | Values and Types |
Variables, Expressions and Statements | Tuple Assignment | Indentation, String Operations | Functions | Illustrative
Programs | Anna University Two Marks Questions & Answers | Multiple Choice Questions

Unit III: Control Flow, Functions, Strings


Control Flow, Functions, Strings | Boolean Values | Operators | Input and Output | Conditional Statements | Iteration
| Fruitful Functions | Recursion | Strings | Lists as arrays | Illustrative Programs | Anna University Two Marks
Questions & Answers | Multiple Choice Questions

Unit IV: Lists, Tuples, Dictionaries


Lists, Tuples, Dictionaries | Lists | Tuples | Dictionaries | Advanced List Processing - List Comprehension | Illustrative
Programs | Anna University Two Marks Questions & Answers | Multiple Choice Questions

Unit V: Files, Modules, Packages


Files, Modules, Packages | Files | Command Line Arguments | Errors and Exceptions | Modules | Packages | Two Marks
Questions with Answers | Multiple Choice Questions

Common to all 1st Semester

HOME | EEE | ECE | MECH | CIVIL | CSE


1st Semester Anna University EEE- Reg 2021
Professional English – I
2nd Semester 3rd Semester
Matrices and Calculus
Probability and Complex
Professional English - II Functions
Engineering Physics
Statistics and Numerical Electromagnetic Fields
Engineering Chemistry Methods
Problem Solving and Physics for Electrical Digital Logic Circuits
Python Programming Engineering
Electron Devices and
Physics and Chemistry Basic Civil and Mechanical Circuits
Laboratory Engineering
Electrical Machines - I
Engineering Graphics
C Programming and Data
4th Semester Electric Circuit Analysis Structures
Environmental Sciences
and Sustainability 6th Semester
Transmission and 5th Semester
Distribution Protection and
Linear Integrated Power System Analysis Switchgear
Circuits
Power Electronics Power System
Measurements and Operation and Control
Instrumentation Control Systems
Open Elective – I
Microprocessor and
Microcontroller Professional Elective I
Professional Elective IV
Electrical Machines - II Professional Elective II
Professional Elective V
Professional Elective III
7th Semester Professional Elective VI
High Voltage Mandatory Course-I& Mandatory Course-
Engineering II& MC
Human Values and 8th Semester
Ethics
Elective –
Management Project Work /
Internship
Open Elective – II
Open Elective – III
Open Elective – IV
Professional Elective
VII Click on Clouds to navigate other department

https://www.poriyaan.in/

You might also like