Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
42 views

Python NOTES Unit-4

Hh

Uploaded by

ashit.mk432
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Python NOTES Unit-4

Hh

Uploaded by

ashit.mk432
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 163

UNIT-1

What is Python? Date:--03/08/2021


Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify
files.
 Python can be used to handle big data and perform complex
mathematics.
 Python can be used for rapid prototyping, or for production-ready
software development.

Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
 Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be very
quick.
 Python can be treated in a procedural way, an object-oriented way or a
functional way.

Good to know
 The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated with
anything other than security updates, is still quite popular.
 In this tutorial Python will be written in a text editor. It is possible to write
Python in an Integrated Development Environment, such as Thonny,
Pycharm, Netbeans or Eclipse which are particularly useful when
managing larger collections of Python files.

Python Syntax compared to other programming languages


 Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as
the scope of loops, functions and classes. Other programming languages
often use curly-brackets for this purpose.

Python interpreter and interactive mode:->


DATE:-04/08/2021
py files are run in the Python interpreter. Interactive mode is a command line shell
which gives immediate feedback for each statement, while running previously fed
statements in active memory. As new lines are fed into the interpreter, the fed
program is evaluated both in part and in whole.

With the Python interactive interpreter it is easy to check Python commands. The
Python interpreter can be invoked by typing the command "python" without any
parameter followed by the "return" key at the shell prompt:

Why to Learn Python?


Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
Python is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning Python:
 Python is Interpreted − Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it. This is similar to PERL
and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

Characteristics of Python
Following are important characteristics of Python Programming −
 It supports functional and structured programming methods as well as OOP.
 It can be used as a scripting language or can be compiled to byte-code for
building large applications.
 It provides very high-level dynamic data types and supports dynamic type
checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Hello World using Python.


Just to give you a little excitement about Python, I'm going to give you a small
conventional Python Hello World program, You can try it using Demo link.
Live Demo
print ("Hello, Python!");

Applications of Python
As mentioned before, Python is one of the most widely used language over the web.
I'm going to list few of them here:
 Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
 Scalable − Python provides a better structure and support for large programs
than shell scripting.

Values to Variables: DATE: 05/08/2021


Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data
types to variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables


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.
The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable. For example −
#!/usr/bin/python

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For
example −
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location. You can also assign multiple objects to multiple
variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

Standard Data Types


The data stored in memory can be of many types. For example, a person's age is
stored as a numeric value and his or her address is stored as alphanumeric characters.
Python has various standard data types that are used to define the operations possible
on them and the storage method for each of them.
Python has five standard data types −

 Numbers
 String
 List
 Tuple
 Dictionary

Python Numbers
Number data types store numeric values. Number objects are created when you assign
a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For
example −
del var
del var_a, var_b
Python supports four different numerical types −

 int (signed integers)


 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −
#!/usr/bin/python

str = 'Hello World!'

print str # Prints complete string


print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

This will produce the following result −


Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists
are similar to arrays in C. One difference between them is that all the items belonging
to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator. For example −
#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

This produce the following result −


['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example

#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')
print tuple # Prints the complete tuple
print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting
from 2nd till 3rd
print tuple[2:] # Prints elements of the tuple starting
from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples

This produce the following result −


('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
The following code is invalid with tuple, because we attempted to update a tuple, which
is not allowed. Similar case is possible with lists −
#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

Python Dictionary 11/08/2021


Python's dictionaries are kind of hash table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example −
#!/usr/bin/python

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key


print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

This produce the following result −


This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.

All data type program running explain on zoom 17/08/2021


Python - Regular Expressions

A regular expression is a special sequence of characters that helps you match or find
other strings or sets of strings, using a specialized syntax held in a pattern. Regular
expressions are widely used in UNIX world.
The Python module re provides full support for Perl-like regular expressions in Python.
The re module raises the exception re.error if an error occurs while compiling or using
a regular expression.
We would cover two important functions, which would be used to handle regular
expressions. But a small thing first: There are various characters, which would have
special meaning when they are used in regular expression. To avoid any confusion
while dealing with regular expressions, we would use Raw Strings as r'expression'.

The match Function


This function attempts to match RE pattern to string with optional flags.
Here is the syntax for this function −
re.match(pattern, string, flags=0)
Here is the description of the parameters −

Sr.No. Parameter & Description

1
pattern
This is the regular expression to be matched.

2
string
This is the string, which would be searched to match the pattern at the beginning of string

3
flags
You can specify different flags using bitwise OR (|). These are modifiers, which are listed i

The re.match function returns a match object on success, None on failure. We


usegroup(num) or groups() function of match object to get matched expression.

Sr.No. Match Object Method & Description

1
group(num=0)
This method returns entire match (or specific subgroup num)

2
groups()
This method returns all matching subgroups in a tuple (empty if there weren't any)

Example

#!/usr/bin/python
import re

line = "Cats are smarter than dogs"

matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)


if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"

When the above code is executed, it produces following result −


matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter

Matching Versus Searching


Python offers two different primitive operations based on regular
expressions: match checks for a match only at the beginning of the string,
while search checks for a match anywhere in the string (this is what Perl does by
default).

Example

Live Demo

#!/usr/bin/python
import re

line = "Cats are smarter than dogs";

matchObj = re.match( r'dogs', line, re.M|re.I)


if matchObj:
print "match --> matchObj.group() : ", matchObj.group()
else:
print "No match!!"

searchObj = re.search( r'dogs', line, re.M|re.I)


if searchObj:
print "search --> searchObj.group() : ", searchObj.group()
else:
print "Nothing found!!"

When the above code is executed, it produces the following result −


No match!!
search --> searchObj.group() : dogs
Search and Replace
One of the most important re methods that use regular expressions is sub.

Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl, substituting
all occurrences unless max provided. This method returns modified string.

Example

Live Demo

#!/usr/bin/python
import re

phone = "2004-959-559 # This is Phone Number"

# Delete Python-style comments


num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num

# Remove anything other than digits


num = re.sub(r'\D', "", phone)
print "Phone Num : ", num

When the above code is executed, it produces the following result −


Phone Num : 2004-959-559
Phone Num : 2004959559

Statement:
A statement is an instruction that the Python interpreter can execute. We
have seen two kinds of statements: print and assignment. When you type
a statement on the command line, Python executes it and displays the
result, if there is one. The result of a print statement is a value.

Python Statement
In Python Programming, any executable instruction, that tell the
computer to perform a specification action is refer to as statements.
These statements are used to build program’s main logic. Program
statement can be an input-output statements, arithmetic statements,
control statements, simple assignment statements and any other
statements and it can also includes comments.
Multi-line statement:- In Python, each of the executable statement
must be ended with a newline character. But, if it required you can
extend a statement over multiple lines explicitly with the line
continuation character (\) as follows –
Example 1:-

1x=1+2+3+\

2 4+5+6+\

3 7+8+9

You can also extend a statement over multiple lines implicitly using
surrounding parentheses ( ), brackets [ ] and braces { }.
Example 2:-

1 x = (1 + 2 + 3 +

2 4+5+6+

3 7 + 8 + 9)

Above multi-line statement is same as in the Example 1

Tuple Assignment
Introduction
Tuples are basically a data type in python. These tuples are an ordered
collection of elements of different data types. Furthermore, we represent
them by writing the elements inside the parenthesis separated by
commas. We can also define tuples as lists that we cannot change.
Therefore, we can call them immutable tuples. Moreover, we access
elements by using the index starting from zero. We can create a tuple in
various ways. Here, we will study tuple assignment which is a very
useful feature in python.

Tuple Assignment
In python, we can perform tuple assignment which is a quite useful
feature. We can initialise or create a tuple in various ways. Besides
tuple assignment is a special feature in python. We also call this
feature unpacking of tuple.

The process of assigning values to a tuple is known as packing. While


on the other hand, the unpacking or tuple assignment is the process that
assigns the values on the right-hand side to the left-hand side variables.
In unpacking, we basically extract the values of the tuple into a single
variable.

Moreover, while performing tuple assignments we should keep in mind


that the number of variables on the left-hand side and the number of
values on the right-hand side should be equal. Or in other words, the
number of variables on the left-hand side and the number of elements in
the tuple should be equal. Let us look at a few examples of packing and
unpacking.

Tuple Packing (Creating Tuples)


We can create a tuple in various ways by using different types of
elements. Since a tuple can contain all elements of the same data type as
well as of mixed data types as well. Therefore, we have multiple ways
of creating tuples. Let us look at few examples of creating tuples in
python which we consider as packing.

Example 1: Tuple with integers as elements

COPY CODE

>>>tup = (22, 33, 5, 23)

>>>tup

(22, 33, 5, 23)

Example 2: Tuple with mixed data type

COPY CODE

>>>tup2 = ('hi', 11, 45.7)

>>>tup2

('hi', 11, 45.7)

Example 3: Tuple with a tuple as an element

COPY CODE

>>>tup3 = (55, (6, 'hi'), 67)

>>>tup3

(55, (6, 'hi'), 67)

Example 4: Tuple with a list as an element

COPY CODE
>>>tup3 = (55, [6, 9], 67)

>>>tup3

(55, [6, 9], 67)

If there is only a single element in a tuple we should end it with a


comma. Since writing, just the element inside the parenthesis will be
considered as an integer.

For example,

COPY CODE

>>>tup=(90)

>>>tup

90

>>>type(tup)

<class 'int'>

Correct way of defining a tuple with single element is as follows:

COPY CODE

>>>tup=(90,)

>>>tup

(90,)

>>>type(tup)
<class 'tuple'>

Moreover, if you write any sequence separated by commas, python


considers it as a tuple.

For example,

COPY CODE

>>> seq = 22, 4, 56

>>>seq

(22, 4, 56)

>>>type(seq)

<class 'tuple'>

Tuple Assignment (Unpacking)


Unpacking or tuple assignment is the process that assigns the values on
the right-hand side to the left-hand side variables. In unpacking, we
basically extract the values of the tuple into a single variable.

Example 1

COPY CODE

>>>(n1, n2) = (99, 7)

>>>print(n1)

99

>>>print(n2)
7

Example 2

COPY CODE

>>>tup1 = (8, 99, 90, 6.7)

>>>(roll no., english, maths, GPA) = tup1

>>>print(english)

99

>>>print(roll no.)

>>>print(GPA)

6.7

>>>print(maths)

90

Example 3

COPY CODE

>>> (num1, num2, num3, num4, num5) = (88, 9.8, 6.8, 1)

#this gives an error as the variables on the left are more than
the number of elements in the tuple

ValueError: not enough values to unpack

(expected 5, got 4)
Python - Basic Operators 18/07/2021

Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.

Types of Operator
Python language supports the following types of operators.

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Let us have a look on all operators one by one.

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description Example

+ Addition Adds values on either side of the a + b = 30


operator.

- Subtraction Subtracts right hand operand from a – b = -10


left hand operand.

* Multiplication Multiplies values on either side of the a * b = 200


operator

/ Division Divides left hand operand by right b/a=2


hand operand

% Modulus Divides left hand operand by right b%a=0


hand operand and returns remainder

** Exponent Performs exponential (power) a**b =10 to the power 20


calculation on operators

// Floor Division - The division of 9//2 = 4 and 9.0//2.0 = 4.0,


operands where the result is the
quotient in which the -11//3 = -4, -11.0//3 = -4.0

digits after the decimal point are


removed. But if one of the operands
is negative,

the result is floored, i.e., rounded


away from zero (towards negative
infinity) −

Python Comparison Operators


These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description

== If the values of two operands are equal, then the condition becomes true.

!= If values of two operands are not equal, then condition becomes true.
<> If values of two operands are not equal, then condition becomes true.

> If the value of left operand is greater than the value of right operand, then condition becomes
true.

< If the value of left operand is less than the value of right operand, then condition becomes true.

>= If the value of left operand is greater than or equal to the value of right operand,

then condition becomes true.

<= If the value of left operand is less than or equal to the value of right operand,

then condition becomes true.

Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description Example

= Assigns values from right side operands to


c = a + b assigns value of a + b into c
left side operand

+= Add AND It adds right operand to the left operand


c += a is equivalent to c = c + a
and assign the result to left operand

-= Subtract AND It subtracts right operand from the left c -= a is equivalent to c = c - a


operand and assign the result to left
operand

*= Multiply AND It multiplies right operand with the left


operand and assign the result to left c *= a is equivalent to c = c * a
operand

/= Divide AND It divides left operand with the right


operand and assign the result to left c /= a is equivalent to c = c / a
operand

%= Modulus AND It takes modulus using two operands and


c %= a is equivalent to c = c % a
assign the result to left operand

**= Exponent AND Performs exponential (power) calculation


on operators and assign
c **= a is equivalent to c = c ** a

value to the left operand

//= Floor Division It performs floor division on operators and


c //= a is equivalent to c = c // a
assign value to the left operand

Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and
b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101
respectively. Following table lists out the bitwise operators supported by Python
language with an example each in those, we use the above two variables (a and b) as
operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
[ Show Example ]

Operator Description Example

& Binary AND Operator copies a bit to the


result if it exists in both (a & b) (means 0000 1100)
operands

| Binary OR It copies a bit if it exists in


(a | b) = 61 (means 0011 1101)
either operand.

^ Binary XOR It copies the bit if it is set in


(a ^ b) = 49 (means 0011 0001)
one operand but not both.

~ Binary Ones (~a ) = -61 (means 1100 0011 in


Complement
It is unary and has the effect of
2's complement form due to a signed binary
'flipping' bits.

number.

<< Binary Left Shift The left operands value is


moved left by the number of
bits specified a << 2 = 240 (means 1111 0000)

by the right operand.

>> Binary Right Shift The left operands value is


moved right by the number of
bits specified a >> 2 = 15 (means 0000 1111)

by the right operand.

Python Logical Operators


There are following logical operators supported by Python language. Assume variable
a holds 10 and variable b holds 20 then
[ Show Example ]

Operator Description Example

and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.

or Logical OR If any of the two operands are (a or b) is true.


non-zero then condition becomes
true.

not Logical NOT Used to reverse the logical state of Not(a and b) is false.
its operand.

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings,
lists, or tuples. There are two membership operators as explained below −
[ Show Example ]

Operator Description Example

in Evaluates to true if it
finds a variable in the
x in y, here in results in a 1 if x is a member of sequence y.
specified sequence
and false otherwise.

not in Evaluates to true if it x not in y, here not in results in a 1 if x is not a member of sequence y.
does not finds a
variable in the specified
sequence and false
otherwise.
Python Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
[ Show Example ]

Operator Description Example

is Evaluates to true if the variables


on either side of the operator
point to
x is y, here is results in 1 if id(x) equals id(y).

the same object and false


otherwise.

is not Evaluates to false if the


variables on either side of the
x is not y, here is not results in 1 if id(x) is not
operator point to

equal to id(y).
the same object and true
otherwise.

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.
[ Show Example ]

Sr.No. Operator & Description

1
**
Exponentiation (raise to the power)

2
~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3
* / % //
Multiply, divide, modulo and floor division

4
+-
Addition and subtraction

5
>> <<
Right and left bitwise shift

6
&
Bitwise 'AND'

7
^|
Bitwise exclusive `OR' and regular `OR'

8
<= < > >=
Comparison operators

9
<> == !=
Equality operators

10
= %= /= //= -= += *= **=
Assignment operators

11
is is not
Identity operators

12
in not in
Membership operators

13
not or and
Logical operators

Python Comments 19/08/2021

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:

Example
#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of
the line:

Example
print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used
to prevent Python from executing code:

Example
#print("Hello, World!")
print("Cheers, Mate!")
Multi Line Comments
Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your comment
inside it:

Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

As long as the string is not assigned to a variable, Python will read the code, but
then ignore it, and you have made a multiline comment.
Python Module 24/08/2021

What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file
extension .py:

Example
Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the


syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):

Example
Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example
Create an alias for mymodule called mx:
import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.

Example
Import and use the platform module:

import platform

x = platform.system()
print(x)

Using the dir() Function


There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:

Example
List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create
yourself.
Import From Module
You can choose to import only parts from a module, by using the from keyword.

Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Note: When importing using the from keyword, do not use the module name
when referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]
Python Function
A function is a block of code which only runs when it is
called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()
Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.


Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.

Example
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

If you try to call the function with 1 or 3 arguments, you will get an error:

Example
This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the
items accordingly:

Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The phrase Keyword Arguments are often shortened to kwargs in Python


documentations.

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.

This way the function will receive a dictionary of arguments, and can access the
items accordingly:

Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Arbitrary Kword Arguments are often shortened to **kwargs in Python


documentations.

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the
function:

Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

The pass Statement


function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid getting
an error.

Example
def myfunction():
pass

end19-8/2021

Recursion 25/08/2021
Python also accepts function recursion, which means a defined function can call
itself.

Recursion is a common mathematical and programming concept. It means that


a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.

Example
Recursion Example

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

programs of python :-

1….# Python program to demonstrate

# swapping of two variables


x = 10

y = 50

# Swapping of two variables

# Using third variable

temp = x

x=y

y = temp

print("Value of x:", x)

print("Value of y:", y)

(2)distance of 2 points….

2. import math

p1 = [4, 0]

p2 = [6, 6]

distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )

print(distance)

(3) circulate n number of variavles:


# Returns the rotated list

def rightRotate(lists, num):

output_list = []

# Will add values from n to the new list

for item in range(len(lists) - num, len(lists)):

output_list.append(lists[item])

# Will add the values before

# n to the end of new list

for item in range(0, len(lists) - num):

output_list.append [item] (lists)

return output_list

# Driver Code

rotate_num = 3

list_1 = [1, 2, 3, 4, 5, 6]

print(rightRotate(list_1, rotate_num))

UNIT-1 END

----------------------------------------------------------------------------------------------------
UNIT-2
Python – LOOPS AND LOOP CONTROL
STATMENT

Date:26/08/2021
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement –

Python programming language provides following types of loops to handle looping


requirements.

Sr.No. Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given condition is TRUE.


It tests the condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code


that manages the loop variable.

3 nested loops

You can use one or more loop inside any another while, for or loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their
detail.
Let us go through the loop control statements briefly

Sr.No. Control Statement & Description

1 break statement

Terminates the loop statement and transfers execution to the statement immediately
following the loop.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.

3 pass statement

The pass statement in Python is used when a statement is required syntactically


but you do not want any command or code to execute.
while loop:
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.

Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python
uses indentation as its method of grouping statements.

Here, key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body will be skipped and the first statement
after the while loop will be executed. Example
#!/usr/bin/python

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

When the above code is executed, it produces the following result −


The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
The block here, consisting of the print and increment statements, is executed
repeatedly until count is no longer less than 9. With each iteration, the current value of
the index count is displayed and then increased by 1.

Python for Loop Statements:

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block
is executed. Each item in the list is assigned to iterating_var, and the statement(s)
block is executed until the entire sequence is exhausted.
Example
#!/usr/bin/python

for letter in 'Python': # First Example


print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"

When the above code is executed, it produces the following result −


Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

Python nested loops


Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.

Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as
follows −
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other type
of loop. For example a for loop can be inside a while loop or vice versa.

Example
The following program uses a nested for loop to find the prime numbers from 2 to 100


#!/usr/bin/python

i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1

print "Good bye!"

When the above code is executed, it produces following result −


2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!

Python break statement

It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.
The most common use for break is when some external condition is triggered requiring
a hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost
loop and start executing the next line of code after the block.

Syntax
The syntax for a break statement in Python is as follows −
break
Flow Diagram

Example
#!/usr/bin/python

for letter in 'Python': # First Example


if letter == 'h':
break
print 'Current Letter :', letter

var = 10 # Second Example


while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break

print "Good bye!"

When the above code is executed, it produces the following result −


Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!

Python continue statement

It returns the control to the beginning of the while loop.. The continue statement
rejects all the remaining statements in the current iteration of the loop and moves the
control back to the top of the loop.
The continue statement can be used in both while and for loops.

Syntax
Continue

Flow Diagram
Example
Live Demo

#!/usr/bin/python

for letter in 'Python': # First Example


if letter == 'h':
continue
print 'Current Letter :', letter

var = 10 # Second Example


while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"

When the above code is executed, it produces the following result −


Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!

Python pass Statement

It is used when a statement is required syntactically but you do not want any command
or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is
also useful in places where your code will eventually go, but has not been written yet
(e.g., in stubs for example) −

Syntax
pass

Example
#!/usr/bin/python

for letter in 'Python':


if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

print "Good bye!"

When the above code is executed, it produces following result −


Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Python if else:- 06/09/2021
There comes situations in real life when we need to make some decisions and based on
these decisions, we decide what should we do next. Similar situations arise in
programming also where we need to make some decisions and based on these decisions
we will execute the next block of code.
Decision-making statements in programming languages decide the direction of the flow
of program execution. Decision-making statements available in python are:

 if statement
 if..else statements
 nested if statements
 if-elif ladder
 Short Hand if statement
 Short Hand if-else statement

if statement
if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition
is true then a block of statement is executed otherwise not.
Syntax:

if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:

if condition:
statement1
statement2

# Here if the condition is true, if block


# will consider only statement1 to be inside
# its block.
Flowchart:-
 Python3

# python program to illustrate If statement

i = 10

if (i > 15):

print ("10 is less than 15")

print ("I am Not in if")

Output:

I am Not in if
As the condition present in the if statement is false. So, the block below the if statement
is not executed.

if-else
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else
if the condition is false. Here comes the else statement. We can use the else statement
with if statement to execute a block of code when the condition is false.
Syntax:

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flow Chart:-

 Python3

# python program to illustrate If else statement

#!/usr/bin/python

i = 20;

if (i < 15):

print ("i is smaller than 15")

print ("i'm in if Block")

else:

print ("i is greater than 15")

print ("i'm in else Block")

print ("i'm not in if and not in else Block")

Output:

i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the
if statement is false after calling the statement which is not in block(without spaces).

nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement. Yes, Python allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:

if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flow chart:-

 Python3

# python program to illustrate nested If statement

#!/usr/bin/python

i = 10

if (i == 10):

# First if statement
if (i < 15):

print ("i is smaller than 15")

# Nested - if statement

# Will only be executed if statement above

# it is true

if (i < 12):

print ("i is smaller than 12 too")

else:

print ("i is greater than 15")

Output:

i is smaller than 15
i is smaller than 12 too
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from the
top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
Syntax:-

if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flow Chart:-

Example:-
 Python3

# Python program to illustrate if-elif-else ladder

#!/usr/bin/python

i = 20

if (i == 10):

print ("i is 10")

elif (i == 15):

print ("i is 15")

elif (i == 20):

print ("i is 20")

else:
print ("i is not present")

Output:

i is 20
Short Hand if statement
Whenever there is only a single statement to be executed inside the if block then
shorthand if can be used. The statement can be put on the same line as the if statement.
Syntax:

if condition: statement
Example:

 Python3

# Python program to illustrate short hand if

i = 10

if i < 15: print("i is less than 15")

Output:

i is less than 15
Short Hand if-else statement
This can be used to write the if-else statements in a single line where there is only one
statement to be executed in both if and else block.
Syntax:

statement_when_True if condition else statement_when_False


Example:

 Python3
# Python program to illustrate short hand if-else

i = 10

print(True) if i < 15 else print(False)

Output:

True

fruitful function: 08/09/2021


A fruitful function can return any type of value may it be string, integer,
boolean, etc. It is not necessary for a fruitful function to return the value of
one variable, the value to be returned can be an array or a vector. A fruitful
function can also return multiple values.

Fruitful functions

5.1 Return values

Some of the built-in functions we have used, such as the math functions, have
produced results. Calling the function generates a new value, which we
usually assign to a variable or use as part of an expression.

e = math.exp(1.0)
height = radius * math.sin(angle)

But so far, none of the functions we have written has returned a value.

In this chapter, we are going to write functions that return values, which we
will call fruitful functions, for want of a better name. The first example
is area, which returns the area of a circle with the given radius:

import math
def area(radius):
temp = math.pi * radius**2
return temp

We have seen the return statement before, but in a fruitful function


the return statement includes a return value. This statement means:
"Return immediately from this function and use the following expression as a
return value." The expression provided can be arbitrarily complicated, so we
could have written this function more concisely:

def area(radius):
return math.pi * radius**2

On the other hand, temporary variables like temp often make debugging
easier.

Sometimes it is useful to have multiple return statements, one in each branch


of a conditional:

def absoluteValue(x):
if x < 0:
return -x
else:
return x

Since these return statements are in an alternative conditional, only one will
be executed. As soon as one is executed, the function terminates without
executing any subsequent statements.

Code that appears after a return statement, or any other place the flow of
execution can never reach, is called dead code.

In a fruitful function, it is a good idea to ensure that every possible path


through the program hits a return statement. For example:

def absoluteValue(x):
if x < 0:
return -x
elif x > 0:
return x
This program is not correct because if x happens to be 0, neither condition is
true, and the function ends without hitting a return statement. In this case,
the return value is a special value called None:

>>> print absoluteValue(0)


None

As an exercise, write a compare function that returns 1 if x > y, 0 if x == y,


and -1 if x < y.

Python - Functions

A function is a block of organized, reusable code that is used to perform a single,


related action. Functions provide better modularity for your application and a high
degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you
can also create your own functions. These functions are called user-defined functions.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.

Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.

Example
The following function takes a string as input parameter and prints it on standard
screen.
def printme( str ):
"This prints a passed string into this function"
print str
return

Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −
Live Demo

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result −


I'm first call to user defined function!
Again second call to the same function

Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means
if you change what a parameter refers to within a function, the change also reflects
back in the calling function. For example −
Live Demo
#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the
same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
Live Demo

#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this
would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]

Function Arguments
You can call a function by using the following types of formal arguments −
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the
function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
Live Demo

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result −


Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways −
Live Demo

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result −


My string
The following example gives more clear picture. Note that the order of parameters
does not matter.
Live Demo

#!/usr/bin/python

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −


Name: miki
Age 50

Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on
default arguments, it prints default age if it is not passed −
Live Demo

#!/usr/bin/python

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −


Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are
not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call. Following is a simple example −
Live Demo

#!/usr/bin/python

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −


Output is:
10
Output is:
70
60
50

The Anonymous Functions


These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
 Lambda forms can take any number of arguments but return just one value in
the form of an expression. They cannot contain commands or multiple
expressions.
 An anonymous function cannot be a direct call to print because lambda requires
an expression
 Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
 Although it appears that lambda's are a one-line version of a function, they are
not equivalent to inline statements in C or C++, whose purpose is by passing
function stack allocation during invocation for performance reasons.

Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo

#!/usr/bin/python

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces the following result −


Value of total : 30
Value of total : 40

The return Statement


The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
All the above examples are not returning any value. You can return a value from a
function as follows −
Live Demo

#!/usr/bin/python

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total

When the above code is executed, it produces the following result −


Inside the function : 30
Outside the function : 30

Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −

 Global variables
 Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they
are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are brought
into scope. Following is a simple example −
Live Demo
#!/usr/bin/python

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

When the above code is executed, it produces the following result −


Inside the function local total : 30
Outside the function global total : 0

Function Composition in Python 09/09/2021


Prerequisite:
Function composition is the way of combining two or more functions in such a way that
the output of one function becomes the input of the second function and so on. For
example, let there be two functions “F” and “G” and their composition can be represented
as F(G(x)) where “x” is the argument and output of G(x) function will become the input
of F() function.
Example:

# Function to add 2

# to a number

def add(x):

return x + 2

# Function to multiply

# 2 to a number
def multiply(x):

return x * 2

# Printing the result of

# composition of add and

# multiply to add 2 to a number

# and then multiply by 2

print("Adding 2 to 5 and multiplying the result with 2:


",

multiply(add(5)))

Output:
Adding 2 to 5 and multiplying the result with 2: 14
Explanation
First the add() function is called on input 5. The add() adds 2 to the input and the output
which is 7, is given as the input to multiply() which multiplies it by 2 and the output is
14.

Recursion in Python
The term Recursion can be defined as the process of defining something in terms of itself.
In simple words, it is a process in which a function calls itself directly or indirectly.

Advantages of using recursion


 A complicated function can be split down into smaller sub-problems utilizing
recursion.
 Sequence creation is simpler through recursion than utilizing any nested iteration.
 Recursive functions render the code look simple and effective.
Disadvantages of using recursion
 A lot of memory and time is taken through recursive calls which makes it expensive
for use.
 Recursive functions are challenging to debug.
 The reasoning behind recursion can sometimes be tough to think through.
Syntax:
def func(): <--
|
| (recursive call)
|
func() ----
Example 1:
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

# Program to print the fibonacci series upto n_terms

# Recursive function

def recursive_fibonacci(n):

if n <= 1:

return n

else:

return(recursive_fibonacci(n-1) +
recursive_fibonacci(n-2))

n_terms = 10
# check if the number of terms is valid

if n_terms <= 0:

print("Invalid input ! Please input a positive


value")

else:

print("Fibonacci series:")

for i in range(n_terms):

print(recursive_fibonacci(i))

Output:

Fibonacci series:
0
1
1
2
3
5
8
13
21
34
Example 2:
The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720.

# Program to print factorial of a number

# recursively.

# Recursive function

def recursive_factorial(n):

if n == 1:

return n

else:

return n * recursive_factorial(n-1)

# user input

num = 6

# check if the input is valid or not

if num < 0:

print("Invalid input ! Please enter a positive


number.")

elif num == 0:
print("Factorial of number 0 is 1")

else:

print("Factorial of number", num, "=",


recursive_factorial(num))

Output:
Factorial of number 6 = 720
Python String
In Python, Strings are arrays of bytes representing Unicode characters. However, Python
does not have a character data type, a single character is simply a string with a length of
1. Square brackets can be used to access elements of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even triple
quotes.

 Python3

# Python Program for

# Creation of String

# Creating a String

# with single Quotes

String1 = 'Welcome to the Geeks World'

print("String with the use of Single Quotes: ")

print(String1)
# Creating a String

# with double Quotes

String1 = "I'm a Geek"

print("\nString with the use of Double Quotes: ")

print(String1)

# Creating a String

# with triple Quotes

String1 = '''I'm a Geek and I live in a world of


"Geeks"'''

print("\nString with the use of Triple Quotes: ")

print(String1)

# Creating String with triple

# Quotes allows multiple lines

String1 = '''Geeks

For

Life'''
print("\nCreating a multiline String: ")

print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:


I'm a Geek

String with the use of Triple Quotes:


I'm a Geek and I live in a world of "Geeks"

Creating a multiline String:


Geeks
For
Life

Accessing characters in Python 14/09/2021


In Python, individual characters of a String can be accessed by using the method of
Indexing. Indexing allows negative address references to access characters from the back
of the String, e.g. -1 refers to the last character, -2 refers to the second last character and
so on.
While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types will cause a TypeError.
 Python3

# Python Program to Access

# characters of String

String1 = "GeeksForGeeks"

print("Initial String: ")

print(String1)

# Printing First character

print("\nFirst character of String is: ")

print(String1[0])

# Printing Last character

print("\nLast character of String is: ")

print(String1[-1])

Output:
Initial String:
GeeksForGeeks

First character of String is:


G
Last character of String is:
s

String Slicing
To access a range of characters in the String, method of slicing is used. Slicing in a String
is done by using a Slicing operator (colon).

 Python3

# Python Program to

# demonstrate String slicing

# Creating a String

String1 = "GeeksForGeeks"

print("Initial String: ")

print(String1)

# Printing 3rd to 12th character

print("\nSlicing characters from 3-12: ")

print(String1[3:12])
# Printing characters between

# 3rd and 2nd last character

print("\nSlicing characters between " +

"3rd and 2nd last character: ")

print(String1[3:-2])

Output:
Initial String:
GeeksForGeeks

Slicing characters from 3-12:


ksForGeek

Slicing characters between 3rd and 2nd last character:


ksForGee

Deleting/Updating from a String


In Python, Updation or deletion of characters from a String is not allowed. This will
cause an error because item assignment or item deletion from a String is not supported.
Although deletion of entire String is possible with the use of a built-in del keyword. This
is because Strings are immutable, hence elements of a String cannot be changed once it
has been assigned. Only new strings can be reassigned to the same name.
Updation of a character:

 Python3

# Python Program to Update

# character of a String
String1 = "Hello, I'm a Geek"

print("Initial String: ")

print(String1)

# Updating a character

# of the String

String1[2] = 'p'

print("\nUpdating character at 2nd Index: ")

print(String1)

Error:
Traceback (most recent call last):
File “/home/360bb1830c83a918fc78aa8979195653.py”, line 10, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment
Updating Entire String:

 Python3

# Python Program to Update

# entire String
String1 = "Hello, I'm a Geek"

print("Initial String: ")

print(String1)

# Updating a String

String1 = "Welcome to the Geek World"

print("\nUpdated String: ")

print(String1)

Output:

Initial String:
Hello, I'm a Geek

Updated String:
Welcome to the Geek World
Deletion of a character:

 Python3

# Python Program to Delete

# characters from a String


String1 = "Hello, I'm a Geek"

print("Initial String: ")

print(String1)

# Deleting a character

# of the String

del String1[2]

print("\nDeleting character at 2nd Index: ")

print(String1)

Error:
Traceback (most recent call last):
File “/home/499e96a61e19944e7e45b7a6e1276742.py”, line 10, in
del String1[2]
TypeError: ‘str’ object doesn’t support item deletion
Deleting Entire String:
Deletion of entire string is possible with the use of del keyword. Further, if we try to print
the string, this will produce an error because String is deleted and is unavailable to be
printed.

 Python3

# Python Program to Delete

# entire String
String1 = "Hello, I'm a Geek"

print("Initial String: ")

print(String1)

# Deleting a String

# with the use of del

del String1

print("\nDeleting entire String: ")

print(String1)

Error:
Traceback (most recent call last):
File “/home/e4b8f2170f140da99d2fe57d9d8c6a94.py”, line 12, in
print(String1)
NameError: name ‘String1’ is not defined

Formatting of Strings
Strings in Python can be formatted with the use of format() method which is very
versatile and powerful tool for formatting of Strings. Format method in String contains
curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.

 Python3
# Python Program for

# Formatting of Strings

# Default order

String1 = "{} {} {}".format('Geeks', 'For', 'Life')

print("Print String in default order: ")

print(String1)

# Positional Formatting

String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')

print("\nPrint String in Positional order: ")

print(String1)

# Keyword Formatting

String1 = "{l} {f} {g}".format(g = 'Geeks', f = 'For', l


= 'Life')

print("\nPrint String in order of Keywords: ")

print(String1)

Output:
Print String in default order:
Geeks For Life

Print String in Positional order:


For Geeks Life

Print String in order of Keywords:


Life For Geeks
Integers such as Binary, hexadecimal, etc. and floats can be rounded or displayed in the
exponent form with the use of format specifiers.

 Python3

# Formatting of Integers

String1 = "{0:b}".format(16)

print("\nBinary representation of 16 is ")

print(String1)

# Formatting of Floats

String1 = "{0:e}".format(165.6458)

print("\nExponent representation of 165.6458 is ")

print(String1)

# Rounding off Integers

String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")

print(String1)

Output:
Binary representation of 16 is
10000

Exponent representation of 165.6458 is


1.656458e+02

one-sixth is :
0.17
A string can be left() or center(^) justified with the use of format specifiers, separated by
colon(:).

 Python3

# String alignment

String1 = "|{:<10}|{:^10}|
{:>10}|".format('Geeks','for','Geeks')

print("\nLeft, center and right alignment with


Formatting: ")

print(String1)

# To demonstrate aligning of spaces

String1 = "\n{0:^16} was founded in


{1:<4}!".format("GeeksforGeeks", 2009)

print(String1)

Output:
Left, center and right alignment with Formatting:
|Geeks | for | Geeks|

GeeksforGeeks was founded in 2009 !


Old style formatting was done without the use of format method by using % operator
 Python3

# Python Program for

# Old Style Formatting

# of Integers

Integer1 = 12.3456789

print("Formatting in 3.2f format: ")

print('The value of Integer1 is %3.2f' %Integer1)

print("\nFormatting in 3.4f format: ")

print('The value of Integer1 is %3.4f' %Integer1)

Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35
Formatting in 3.4f format:
The value of Integer1 is 12.3457

What is the string function in Python?

Python string encode() function is used to encode the string using the
provided encoding. Python String count() function returns the number
of occurrences of a substring in the given string. Python string
startswith() function returns True if the string starts with the given
prefix, otherwise it returns False.

Python String Method


Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original
string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in


a string
encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the
position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the
position of where it was found

isalnum() Returns True if all characters in the string are


alphanumeric

isalpha() Returns True if all characters in the string are in the


alphabet

isascii() Returns True if all characters in the string are ascii


characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are


whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper


case
join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three


parts

replace() Returns a string where a specified value is replaced with


a specified value

rfind() Searches the string for a specified value and returns the
last position of where it was found

rindex() Searches the string for a specified value and returns the
last position of where it was found

rjust() Returns a right justified version of the string


rpartition() Returns a tuple where the string is parted into three
parts

rsplit() Splits the string at the specified separator, and returns a


list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a


list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice
versa

title() Converts the first character of each word to upper case

translate() Returns a translated string


upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the


beginning

Note: All string methods returns new values. They do not change the original
string.

How to convert a list to an array in


Python date:--15/09/2021
During programming, there will be instances when you will need to convert
existing lists to arrays in order to perform certain operations on them (arrays
enable mathematical operations to be performed on them in ways that lists do
not).
Lists can be converted to arrays using the built-in functions in the
Python numpy library.

numpyprovides us with two functions to use when converting a list into an


array:
 numpy.array()
 numpy.asarray()

1. Using numpy.array()
This function of the numpy library takes a list as an argument and returns an
array that contains all the elements of the list. See the example below:
7

import numpy as np

my_list = [2,4,6,8,10]

my_array = np.array(my_list)

# printing my_array

print my_array

# printing the type of my_array

print type(my_array)

Run

2. Using numpy.asarray()
This function calls the numpy.array() function inside itself. See the definition
below:

def asarray(a, dtype=None, order=None):


return array(a, dtype, copy=False, order=order)

The main difference between np.array() and np.asarray() is that the copy flag
is false in the case of np.asarray(), and true (by default) in the case of np.array().

This means that np.array() will make a copy of the object (by default) and
convert that to an array, while np.asarray() will not.

The code below illustrates the usage of np.asarray():


import numpy as np
my_list = [2,4,6,8,10]
my_array = np.asarray(my_list)
# printing my_array
print my_array
# printing the type of my_array
print type(my_array)

program of 2nd unit :-

1.square root program in python……

1. Using Exponent

1 number = int(input("enter a number: "))


2 sqrt = number ** 0.5
3
print("square root:", sqrt)
Output:

enter a number: 64
square root: 8.0

In above program, first we’re taking a number from user as input and the
entered value will be converted to int from string and will store into variable
called number. Then we are using exponent (**) sign, which is used to find
out the power of a number. But we know that if a number have power ½ or 0.5
then it will represent to the square root of that number. That’s why we are
using 0.5 as power here. So the number**0.5 will give us square root of that
number and will be stored in variable named as sqrt. In last line we’re just
printing the square root of the number.

2. Using math.sqrt() Method


1
import math
2 number = int(input("enter a number:"))
3
4
sqrt = math.sqrt(number)
print("square root:" , sqrt)
sqrt() is the predefined method used to find square root in python. But we
have to import math module to use the sqrt() method. In first line, we’re
importing math module, then in next line, taking input from user. After that
we’re finding the square root of the number using sqrt() method and result will
be stored into sqrt variable. In last line, just printing the square root as in first
program.

3. Using math.pow() Method

1
import math
2 number = int(input("enter a number:"))
3
4
sqrt = math.pow(number, 0.5)
print("square root: ", sqrt)
pow() is also a predefined method to find out power of a number, it takes two
arguments as input, first is the number itself and second one is power of that
number. The program is same as first program where we’re using (**) sign to
find out the square root but only different is this that here we’re using a
predefined method pow() instead of (**) sign to get the power of that
number.

If you’ve any problem related with article or have any other possible way to find
square root in python then please let us know in comments.

Program:--
# Python Program to calculate the square root

# Note: change this value for a different result


num = 8

# To take the input from the user


#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5


print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

2. find the gcd in python:--

Python program to find the gcd of two numbers


Given two numbers. The task is to find the GCD of the two numbers.
Using STL :
In Python, the math module contains a number of mathematical operations, which can be
performed with ease using the module. math.gcd() function compute the greatest
common divisor of 2 numbers mentioned in its arguments.
Syntax: math.gcd(x, y)
Parameter:
x : Non-negative integer whose gcd has to be computed.
y : Non-negative integer whose gcd has to be computed.
Returns: An absolute/positive integer value after calculating the GCD of given
parameters x and y.
Exceptions: When Both x and y are 0, function returns 0, If any number is a character,
Type error is raised.
 Python3

# Python code to demonstrate the working of


gcd()

# importing "math" for mathematical


operations
import math

# prints 12

print("The gcd of 60 and 48 is : ", end="")

print(math.gcd(60, 48))

Output

The gcd of 60 and 48 is : 12


3.sum an array of numbers……

3..Python program to print the sum of all


elements in an array
In this program, we need to calculate the sum of all the elements of an array. This can be
solved by looping through the array and add the value of the element in each iteration
to variable sum.

Sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.

ALGORITHM:
o STEP 1: Declare and initialize an array.
o STEP 2: The variable sum will be used to calculate the sum of the elements.
Initialize it to 0.
o STEP 3: Loop through the array and add each element of the array to the variable
sum as sum = sum + arr[i].
PROGRAM:
# of elements in given array

# driver function

arr = []

# input values to list

arr = [12, 3, 4, 15]

# sum() is an inbuilt function in python that adds

# all the elements in list,set and tuples and returns

# the value

ans = sum(arr)

# display sum

print ('Sum of the array is ',ans)

# This code is contributed by Dhananjay Patil

Output:- Sum of the array is 34

4.linear search in python:


Python Program for Linear Search
Problem: Given an array arr[] of n elements, write a function to search a given element x
in arr[].
Examples :
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 110;
Output : 6
Element x is present at index 6

Input : arr[] = {10, 20, 80, 30, 60, 50,


110, 100, 130, 170}
x = 175;
Output : -1
Element x is not present in arr[].
A simple approach is to do linear search, i.e
 Start from the leftmost element of arr[] and one by one compare x with each element
of arr[]
 If x matches with an element, return the index.
 If x doesn’t match with any of elements, return -1.
# Searching an element in a list/array in python

# can be simply done using \'in\' operator

# Example: Mutable vs
# if x in arr:
Immutable
Objects in
# print arr.index(x) Python
21/09/2021
Every variable in
python holds an
# If you want to implement Linear Search in python instance of an
object. There are
two types of objects
in python
# Linearly search x in arr[] i.e. Mutable and I
mmutable objects.
# If x is present then return its location Whenever an object
is instantiated, it is
# else return -1 assigned a unique
object id. The type
of the object is
defined at the
runtime and it can’t
def search(arr, x):
be changed
afterwards.
However, it’s state
can be changed if it
for i in range(len(arr)): is a mutable object.
To summarise the
difference, mutable
objects can change
if arr[i] == x: their state or
contents and
return i immutable objects
can’t change their
return -1 state or content.
 Immutable
Objects : These
are of in-built
5.Binary search in python: types like int,
date:16/09/2021 float, bool,

Recursive
Example
def binarySearchAppr (arr, start, end, x):
# check condition
string, unicode, tuple. In simple words, an immutable object can’t be changed after it
is created.

# Python code to test that

# tuples are immutable

tuple1 = (0, 1, 2, 3)

tuple1[0] = 4

print(tuple1)

 Error :
 Traceback (most recent call last):
 File "e0eaddff843a8695575daec34506f126.py", line 3, in
 tuple1[0]=4
 TypeError: 'tuple' object does not support item assignment

# Python code to test that

# strings are immutable

message = "Welcome to GeeksforGeeks"

message[0] = 'p'

print(message)
 Error :
 Traceback (most recent call last):
 File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
 message[0] = 'p'
 TypeError: 'str' object does not support item assignment
 Mutable Objects : These are of type list, dict, set . Custom classes are generally
mutable.

# Python code to test that

# lists are mutable

color = ["red", "blue", "green"]

print(color)

color[0] = "pink"

color[-1] = "orange"

print(color)

 Output:

 ['red', 'blue', 'green']


 ['pink', 'blue', 'orange']
Aliasing:
An alias is a a second name for a piece of data. ... In Python,
aliasing happens whenever one variable's value is assigned to another
variable, because variables are just names that store references to values.

Python Passing a List as an


Argument

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the
function:

Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

9. Tuples: 23/09/2021
tuple AssIgnment: One of the unique syntactic features of the Python language is
the ability to have a tuple on the left side of an assignment statement. This allows
you to assign more than one variable at a time when the left side is a sequence.
Tuples

9.1. Tuples are used for grouping data


We saw earlier that we could group together pairs of values by surrounding with
parentheses. Recall this example:

>>> year_born = ("Paris Hilton", 1981)

This is an example of a data structure — a mechanism for grouping and organizing data to
make it easier to use.

The pair is an example of a tuple. Generalizing this, a tuple can be used to group any
number of items into a single compound value. Syntactically, a tuple is a comma-separated
sequence of values. Although it is not necessary, it is conventional to enclose tuples in
parentheses:

>>> julia = ("Julia", 1967"Roberts",, "Duplicity", 2009, "Actress", "Atlanta,


Georgia")

Tuples are useful for representing what other languages often call records — some related
information that belongs together, like your student record. There is no description of what
each of these fields means, but we can guess. A tuple lets us “chunk” together related
information and use it as a single thing.

Tuples support the same sequence operations as strings. The index operator selects an
element from a tuple.

>>> julia[2]
1967

But if we try to use item assignment to modify one of the elements of the tuple, we get an
error:

>>> julia[0] = "X"


TypeError: 'tuple' object does not support item assignment

So like strings, tuples are immutable. Once Python has created a tuple in memory, it cannot
be changed.
Of course, even if we can’t modify the elements of a tuple, we can always make
the julia variable reference a new tuple holding different information. To construct the new
tuple, it is convenient that we can slice parts of the old tuple and join up the bits to make the
new tuple. So if julia has a new recent film, we could change her variable to reference a new
tuple that used some information from the old one:

>>> julia = julia[:3] + ("Eat Pray Love", 2010) + julia[5:]


>>> julia
("Julia", "Roberts", 1967, "Eat Pray Love", 2010, "Actress", "Atlanta, Georgia")

To create a tuple with a single element (but you’re probably not likely to do that too often),
we have to include the final comma, because without the final comma, Python treats
the (5) below as an integer in parentheses:

>>> tup = (5,)


>>> type(tup)
<class 'tuple'>
>>> x = (5)
>>> type(x)
<class 'int'>

9.2. Tuple assignment


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 assignment. (We
already saw this used for pairs, but it generalizes.)

(name, surname, b_year, movie, m_year, profession, b_place) = julia

This does the equivalent of seven assignment statements, all on one easy line. One
requirement is that the number of variables on the left must match the number of elements
in the tuple.

One way to think of tuple assignment is as tuple packing/unpacking.

In tuple packing, the values on the left are ‘packed’ together in a tuple:

>>> b = ("Bob", 19, "CS") # tuple packing

In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names
on the right:

>>> b = ("Bob", 19, "CS")


>>> (name, age, studies) = b # tuple unpacking
>>> name
'Bob'
>>> age
19
>>> studies
'CS'

Once in a while, it is useful to swap the values of two variables. With conventional
assignment statements, we have to use a temporary variable. For example, to swap a and b:

1 temp = a
2 a = b
3 b = temp

Tuple assignment solves this problem neatly:

(a, b) = (b,
1
a)

The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned
to its respective variable. All the expressions on the right side are evaluated before any of
the assignments. This feature makes tuple assignment quite versatile.

Naturally, the number of variables on the left and the number of values on the right have to
be the same:

>>> (a, b, c, d) = (1, 2, 3)


ValueError: need more than 3 values to unpack

9.3. Tuples as return values


Functions can always only return a single value, but by making that value a tuple, we can
effectively group together as many values as we like, and return them together. This is very
useful — we often want to know some batsman’s highest and lowest score, or we want to
find the mean and the standard deviation, or we want to know the year, the month, and the
day, or if we’re doing some some ecological modelling we may want to know the number of
rabbits and the number of wolves on an island at a given time.

For example, we could write a function that returns both the area and the circumference of a
circle of radius r:

1
def f(r):
2
""" Return (circumference, area) of a circle of radius r """
3
c = 2 * math.pi * r
4
a = math.pi * r * r
5
return (c, a)

Python Dictionary:
Dictionary in Python is an unordered collection of data values, used to store data values
like a map, which, unlike other Data Types that hold only a single value as an element,
Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more
optimized.

Note – Keys in a dictionary don’t allow Polymorphism.


Disclamer: It is important to note that Dictionaries have been modified to maintain
insertion order with the release of Python 3.7, so they are now ordered collection of data
values.
Creating a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the
Key and the other corresponding pair element being its Key:value. Values in a dictionary
can be of any data type and can be duplicated, whereas keys can’t be repeated and must
be immutable.

Note – Dictionary keys are case sensitive, the same name but different cases of Key will
be treated distinctly.

 Python3

# Creating a Dictionary

# with Integer Keys

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

print("\nDictionary with the use of Integer Keys: ")

print(Dict)
# Creating a Dictionary

# with Mixed keys

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}

print("\nDictionary with the use of Mixed Keys: ")

print(Dict)

Output:

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:


{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing to curly braces{}.

 Python3

# Creating an empty Dictionary

Dict = {}

print("Empty Dictionary: ")

print(Dict)
# Creating a Dictionary

# with dict() method

Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})

print("\nDictionary with the use of dict(): ")

print(Dict)

# Creating a Dictionary

# with each item as a Pair

Dict = dict([(1, 'Geeks'), (2, 'For')])

print("\nDictionary with each item as a pair: ")

print(Dict)

Output:
Empty Dictionary:
{}

Dictionary with the use of dict():


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:


{1: 'Geeks', 2: 'For'}
Nested Dictionary:

 Python3

# Creating a Nested Dictionary

# as shown in the below image

Dict = {1: 'Geeks', 2: 'For',

3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}


print(Dict)

Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

Adding elements to a Dictionary


In Python Dictionary, the Addition of elements can be done in multiple ways. One value
at a time can be added to a Dictionary by defining value along with the key e.g.
Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can be done by using the
built-in update() method. Nested key values can also be added to an existing Dictionary.

Note- While adding a value, if the key-value already exists, the value gets updated
otherwise a new Key with the value is added to the Dictionary.
 Python3

# Creating an empty Dictionary

Dict = {}

print("Empty Dictionary: ")

print(Dict)

# Adding elements one at a time


Dict[0] = 'Geeks'

Dict[2] = 'For'

Dict[3] = 1

print("\nDictionary after adding 3 elements: ")

print(Dict)

# Adding set of values

# to a single Key

Dict['Value_set'] = 2, 3, 4

print("\nDictionary after adding 3 elements: ")

print(Dict)

# Updating existing Key's Value

Dict[2] = 'Welcome'

print("\nUpdated key value: ")

print(Dict)

# Adding Nested Key value to Dictionary


Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}

print("\nAdding a Nested Key: ")

print(Dict)

Output:
Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Geeks', 2: 'For', 3: 1}

Dictionary after adding 3 elements:


{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value:


{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'Geeks', 2: 'Welcome', 3: 1, 5: {'Nested': {'1': 'Life', '2':
'Geeks'}}, 'Value_set': (2, 3, 4)}

Accessing elements from a Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets.

 Python3

# Python program to demonstrate


# accessing a element from a Dictionary

# Creating a Dictionary

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key

print("Accessing a element using key:")

print(Dict['name'])

# accessing a element using key

print("Accessing a element using key:")

print(Dict[1])

Output:
Accessing a element using key:
For

Accessing a element using key:


Geeks
There is also a method called get() that will also help in accessing the element from a
dictionary.
 Python3
# Creating a Dictionary

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using get()

# method

print("Accessing a element using get:")

print(Dict.get(3))

Output:
Accessing a element using get:
Geeks

Accessing an element of a nested dictionary

In order to access the value of any key in the nested dictionary, use indexing [] syntax.

 Python3

# Creating a Dictionary

Dict = {'Dict1': {1: 'Geeks'},

'Dict2': {'Name': 'For'}}

# Accessing element using key


print(Dict['Dict1'])

print(Dict['Dict1'][1])

print(Dict['Dict2']['Name'])

Output:
{1: 'Geeks'}
Geeks
For

Removing Elements from Dictionary


Using del keyword

In Python Dictionary, deletion of keys can be done by using the del keyword. Using the
del keyword, specific values from a dictionary as well as the whole dictionary can be
deleted. Items in a Nested dictionary can also be deleted by using the del keyword and
providing a specific nested key and particular key to be deleted from that nested
Dictionary.

Note: The del Dict will delete the entire dictionary and hence printing it after deletion
will raise an Error.
 Python3

# Initial Dictionary

Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',

'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},


'B' : {1 : 'Geeks', 2 : 'Life'}}

print("Initial Dictionary: ")

print(Dict)

# Deleting a Key value

del Dict[6]

print("\nDeleting a specific key: ")

print(Dict)

# Deleting a Key from

# Nested Dictionary

del Dict['A'][2]

print("\nDeleting a key from Nested Dictionary: ")

print(Dict)

Output:
Initial Dictionary:
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2:
'Life'}, 5: 'Welcome', 6: 'To', 7: 'Geeks'}

Deleting a specific key:


{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2:
'Life'}, 5: 'Welcome', 7: 'Geeks'}
Deleting a key from Nested Dictionary:
{'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5:
'Welcome', 7: 'Geeks'}

Using pop() method

Pop() method is used to return and delete the value of the key specified.
 Python3

# Creating a Dictionary

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Deleting a key

# using pop() method

pop_ele = Dict.pop(1)

print('\nDictionary after deletion: ' + str(Dict))

print('Value associated to poped key is: ' +


str(pop_ele))

Output:
Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
Value associated to poped key is: Geeks

Using popitem() method

The popitem() returns and removes an arbitrary element (key, value) pair from the
dictionary.

 Python3
# Creating Dictionary

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Deleting an arbitrary key

# using popitem() function

pop_ele = Dict.popitem()

print("\nDictionary after deletion: " + str(Dict))

print("The arbitrary pair returned is: " +


str(pop_ele))

Output:
Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
The arbitrary pair returned is: (1, 'Geeks')

Using clear() method

All the items from a dictionary can be deleted at once by using clear() method.
 Python3

# Creating a Dictionary

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


# Deleting entire Dictionary

Dict.clear()

print("\nDeleting Entire Dictionary: ")

print(Dict)

Output:
Deleting Entire Dictionary:
{}

Dictionary Methods
Methods Description

copy() They copy() method returns a shallow copy of the dictionary.

clear() The clear() method removes all items from the dictionary.

Removes and returns an element from a dictionary having the


pop() given key.

Removes the arbitrary key-value pair from the dictionary and


popitem() returns it as tuple.

get() It is a conventional method to access a value for a key.

dictionary_name.values()returns a list of all the values available in a given dictionary.

str() Produces a printable string representation of a dictionary.

update() Adds dictionary dict2’s key-values pairs to dict

setdefault() Set dict[key]=default if key is not already in dict

keys() Returns list of dictionary dict’s keys

items() Returns a list of dict’s (key, value) tuple pairs

has_key() Returns true if key in dictionary dict, false otherwise


Create a new dictionary with keys from seq and values set to
fromkeys() value.

type() Returns the type of the passed variable.

cmp() Compares elements of both dict.

Advanced list processing:04/10/2021

1. Python Examples on Searching Algorithms


The Python programs in this section illustrate searching algorithms. Linear search is a
method for finding a particular value in a list. It starts searching the value from the beginning
of the list and continues till the end of the list until the value is found. Binary search is an
algorithm for locating the position of an item in a sorted array. The following python
programs implements linear search and binary search algorithms with and without using
recursion. It also finds the smallest and largest elements from the list in a expected linear
time.

Python Program to Implement Linear Search


Python Program to Implement Binary Search without Recursion
Python Program to Implement Binary Search with Recursion
Python Program to Select the ith Smallest Element from a List in Expected Linear Time
Python Program to Select the ith Largest Element from a List in Expected Linear Time

Python Program to Implement Linear Search

This is a Python program to implement linear search.

Problem Description
The program takes a list and key as input and finds the index of the key in the list using
linear search.

Problem Solution
1. Create a function linear_search that takes a list and key as arguemnts.
2. A loop iterates through the list and when an item matching the key is found, the
corresponding index is returned.
3. If no such item is found, -1 is returned.

Program/Source Code
Here is the source code of a Python program to implement linear search. The program
output is shown below.

def linear_search(alist, key):


"""Return index of key in alist. Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1

alist = input('Enter the list of numbers: ')


alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = linear_search(alist, key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The user is then asked to enter a key to search for.
3. The list and key is passed to linear_search.
4. If the return value is -1, the key is not found and a message is displayed, otherwise the
index of the found item is displayed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 5 4 3 2 1 10 11 2
The number to search for: 1
1 was found at index 4.

Case 2:
Enter the list of numbers: 5 2 1 5 -3
The number to search for: 2
2 was found at index 1.

Case 3:
Enter the list of numbers: 3 5 6
The number to search for: 2
2 was not found.

2. Python Examples on Sorting Algorithms


Bubble sort is a sorting algorithm that works by repeatedly stepping through the list to be
sorted, comparing each pair of adjacent items and swaps them if they are in the wrong
position. Heapsort is a comparison based sorting algorithm. It is similar to a selection sort
algorithm. Selection sort algorithm sort the data by comparing one element to every other
element and decides its position. Quick sort is based on an algorithmic design pattern called
divide and conquer. It is mainly used for sorting numbers, structure and files. Merge Sort
divides the input array into two halves, sorts the two halves and merges the two sorted
halves. Insertion Sort algorithm sorts the array by shifting the elements one by one. Gnome
sort algorithm sorts the items by comparing the current item with the previous item. For
example if they are in order, move to the next item. If they are out of order, swap them and
move to the previous item. If there is no previous item, move to the next item. The Python
programs in this section demonstrates special sorting algorithms like bubble sort, selection
sort, merge sort, quicksort, heap sort, comb sort, shell sort, gnome sort, introsort and bucket
sort.

Python Program to Implement Bubble Sort


Python Program to Implement Selection Sort
Python Program to Implement Insertion Sort
Python Program to Implement Merge Sort
Python Program to Implement Quicksort
Python Program to Implement Heapsort
Python Program to Implement Counting Sort
Python Program to Implement Radix Sort
Python Program to Implement Bucket Sort
Python Program to Implement Gnome Sort
Python Program to Implement Cocktail Shaker Sort
Python Program to Implement Comb Sort
Python Program to Implement Shell Sort
Python Program to Implement Introsort

Python Program to Implement Bubble Sort


This is a Python program to implement bubble sort.

Problem Description
The program sorts a list by bubble sort.

Problem Solution
1. Create a function bubble_sort that takes a list as argument.
2. Inside the function create a loop with a loop variable i that counts from the length of the
list – 1 to 1.
3. Create an inner loop with a loop variable that counts from 0 up to i – 1.
4. Inside the inner loop, if the elements at indexes j and j + 1 are out of order, then swap
them.
5. If in one iteration of the inner loop there were no swaps, then the list is sorted and one
can return prematurely.
Program/Source Code
Here is the source code of a Python program to implement bubble sort. The program output
is shown below.

def bubble_sort(alist):
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if no_swap:
return

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted list: ', end='')
print(alist)
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The list is passed to the bubble_sort function.
3. The sorted list is displayed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 4 2 38 10 5
Sorted list: [2, 4, 5, 10, 38]

Case 2:
Enter the list of numbers: 5 4 3 2 1
Sorted list: [1, 2, 3, 4, 5]

Case 3:
Enter the list of numbers: 7 3 1 -5 2 10
Sorted list: [-5, 1, 2, 3, 7, 10]

END UNIT 3rd


UNIT-IV CLASS AND INHERITANCE 05/10/2021

OOP Python:
Python is a great programming language that supports OOP. You will use it to define a class
with attributes and methods, which you will then call. Python offers a number of benefits
compared to other programming languages like Java, C++ or R. It's a dynamic language, with
high-level data types

Python Object-Oriented
Programming (OOP):
Tackle the basics of Object-Oriented Programming (OOP)
in Python: explore classes, objects, instance methods,
attributes and much more!

Object-Oriented programming is a widely used concept to write powerful


applications. As a data scientist, you will be required to write applications to
process your data, among a range of other things. In this tutorial, you will
discover the basics of object-oriented programming in Python. You will learn
the following:

 How to create a class


 Instantiating objects

 Adding attributes to a class

 Defining methods within a class

 Passing arguments to methods


OOP: Introduction
Object-oriented programming has some advantages over other design
patterns. Development is faster and cheaper, with better software
maintainability. This, in turn, leads to higher-quality software, which is also
extensible with new methods and attributes. The learning curve is, however,
steeper. The concept may be too complex for beginners. Computationally,
OOP software is slower, and uses more memory since more lines of code
have to be written.

Object-oriented programming is based on the imperative programming


paradigm, which uses statements to change a program's state. It focuses on
describing how a program should operate. Examples of imperative
programming languages are C, C++, Java, Go, Ruby and Python. This stands
in contrast to declarative programming, which focuses on what the computer
program should accomplish, without specifying how. Examples are database
query languages like SQL and XQuery, where one only tells the computer
what data to query from where, but now how to do it.

OOP uses the concept of objects and classes. A class can be thought of as a
'blueprint' for objects. These can have their own attributes (characteristics
they possess), and methods (actions they perform).

OOP Example
An example of a class is the class Dog. Don't think of it as a specific dog, or
your own dog. We're describing what a dog is and can do, in general. Dogs
usually have a name and age; these are instance attributes. Dogs can
also bark; this is a method.
When you talk about a specific dog, you would have an object in
programming: an object is an instantiation of a class. This is the basic
principle on which object-oriented programming is based. So my dog Ozzy,
for example, belongs to the class Dog. His attributes are name =
'Ozzy' and age = '2'. A different dog will have different attributes.

OOP in Python
Python is a great programming language that supports OOP. You will use it
to define a class with attributes and methods, which you will then call.
Python offers a number of benefits compared to other programming
languages like Java, C++ or R. It's a dynamic language, with high-level data
types. This means that development happens much faster than with Java or
C++. It does not require the programmer to declare types of variables and
arguments. This also makes Python easier to understand and learn for
beginners, its code being more readable and intuitive.

If you're new to Python, be sure to take a look at DataCamp's Intro to Python


for Data Science course.

How to create a class


To define a class in Python, you can use the class keyword, followed by the
class name and a colon. Inside the class, an __init__ method has to be
defined with def. This is the initializer that you can later use to instantiate
objects. It's similar to a constructor in Java. __init__ must always be
present! It takes one argument: self, which refers to the object itself. Inside
the method, the pass keyword is used as of now, because Python expects
you to type something there. Remember to use correct indentation!
class Dog:
def __init__(self):

pass

Note: self in Python is equivalent to this in C++ or Java.

In this case, you have a (mostly empty) Dog class, but no object yet. Let's
create one!

Instantiating objects
To instantiate an object, type the class name, followed by two brackets. You
can assign this to a variable to keep track of the object.
ozzy = Dog()

And print it:


print(ozzy)

<__main__.Dog object at 0x111f47278>

Adding attributes to a class


After printing ozzy, it is clear that this object is a dog. But you haven't added
any attributes yet. Let's give the Dog class a name and age, by rewriting it:
class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

You can see that the function now takes two arguments
after self: name and age. These then get assigned
to self.name and self.age respectively. You can now now create a
new ozzy object, with a name and age:
ozzy = Dog("Ozzy", 2)

To access an object's attributes in Python, you can use the dot notation. This
is done by typing the name of the object, followed by a dot and the attribute's
name.
print(ozzy.name)

print(ozzy.age)

Ozzy
2

This can also be combined in a more elaborate sentence:


print(ozzy.name + " is " + str(ozzy.age) + " year(s) old.")

Ozzy is 2 year(s) old.

The str() function is used here to convert the age attribute, which is an
integer, to a string, so you can use it in the print() function.

Define methods in a class


Now that you have aDog class, it does have a name and age which you can
keep track of, but it doesn't actually do anything. This is where instance
methods come in. You can rewrite the class to now include
a bark() method. Notice how the def keyword is used again, as well as
the self argument.
class Dog:

def __init__(self, name, age):

self.name = name

self.age = age
def bark(self):

print("bark bark!")

The bark method can now be called using the dot notation, after instantiating
a new ozzy object. The method should print "bark bark!" to the screen.
Notice the parentheses (curly brackets) in .bark(). These are always used
when calling a method. They're empty in this case, since the bark() method
does not take any arguments.
ozzy = Dog("Ozzy", 2)

ozzy.bark()

bark bark!

Recall how you printed ozzy earlier? The code below now implements this
functionality in the Dog class, with the doginfo() method. You then
instantiate some objects with different properties, and call the method on
them.
class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

print("bark bark!")

def doginfo(self):
print(self.name + " is " + str(self.age) + " year(s)

old.")

ozzy = Dog("Ozzy", 2)

skippy = Dog("Skippy", 12)

filou = Dog("Filou", 8)

ozzy.doginfo()

skippy.doginfo()

filou.doginfo()

Ozzy is 2 year(s) old.

Skippy is 12 year(s) old.

Filou is 8 year(s) old.

As you can see, you can call the doginfo() method on objects with the dot
notation. The response now depends on which Dog object you are calling the
method on.

Since dogs get older, it would be nice if you could adjust their age
accordingly. Ozzy just turned 3, so let's change his age.
ozzy.age = 3

print(ozzy.age)

It's as easy as assigning a new value to the attribute. You could also
implement this as a birthday() method in the Dog class:
class Dog:

def __init__(self, name, age):

self.name = name
self.age = age

def bark(self):

print("bark bark!")

def doginfo(self):

print(self.name + " is " + str(self.age) + " year(s)

old.")

def birthday(self):

self.age +=1

ozzy = Dog("Ozzy", 2)

print(ozzy.age)

ozzy.birthday()

print(ozzy.age)

Now, you don't need to manually change the dog's age. whenever it is its
birthday, you can just call the birthday() method.

Passing arguments to methods


You would like for our dogs to have a buddy. This should be optional, since
not all dogs are as sociable. Take a look at the setBuddy() method below. It
takes self, as per usual, and buddy as arguments. In this case, buddy will
be another Dog object. Set the self.buddy attribute to buddy, and
the buddy.buddy attribute to self. This means that the relationship is
reciprocal; you are your buddy's buddy. In this case, Filou will be Ozzy's
buddy, which means that Ozzy automatically becomes Filou's buddy. You
could also set these attributes manually, instead of defining a method, but that
would require more work (writing 2 lines of code instead of 1) every time
you want to set a buddy. Notice that in Python, you don't need to specify of
what type the argument is. If this were Java, it would be required.
class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

print("bark bark!")

def doginfo(self):

print(self.name + " is " + str(self.age) + " year(s)

old.")

def birthday(self):

self.age +=1

def setBuddy(self, buddy):

self.buddy = buddy

buddy.buddy = self

You can now call the method with the dot notation, and pass it
another Dog object. In this case, Ozzy's buddy will be Filou:
ozzy = Dog("Ozzy", 2)
filou = Dog("Filou", 8)

ozzy.setBuddy(filou)

If you now want to get some information about Ozzy's buddy, you can use
the dot notation twice:. First, to refer to Ozzy's buddy, and a second time to
refer to its attribute.
print(ozzy.buddy.name)

print(ozzy.buddy.age)
Filou

Notice how this can also be done for Filou.


print(filou.buddy.name)

print(filou.buddy.age)

Ozzy

The buddy's methods can also be called. The self argument that gets passed
to doginfo() is now ozzy.buddy, which is filou.
ozzy.buddy.doginfo()
Filou is 8 year(s) old.

INHERITANCE Ii

INHERITANCE IN PYTHONE 08 /10/2021

Data Scien
Inheritance In Python With Examples: All You Need To Know

Python programming language is easy to learn and works on both procedural and object oriented
programming approach. Inheritance is one such concept in object oriented programming. Code
reusability being the forte of inheritance, it helps in a lot of applications when we are working on
Python. Following are the concepts discussed in this article:

 What Is Inheritance?
 init Function
 Types Of Inheritance
o Single Inheritance
o Multiple Inheritance
o Multilevel Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
 Python super() Function
 Python Method Overriding

What Is Inheritance?
The method of inheriting the properties of parent class into a child class is known as inheritance.
It is an OOP concept. Following are the benefits of inheritance.

1. Code reusability- we do not have to write the same code again and again, we can just
inherit the properties we need in a child class.

2. It represents a real world relationship between parent class and child class.

3. It is transitive in nature. If a child class inherits properties from a parent class, then all
other sub-classes of the child class will also inherit the properties of the parent class.

Below is a simple example of inheritance in python.

1 class Parent():

2 def first(self):

print('first function')
3

4
class Child(Parent):
5
def second(self):
6
print('second function')
7

8
ob = Child()
9
ob.first()
10
ob.second()
11

Output:
first function
second function
In the above program, you can access the parent class function using the child class object.

Sub-classing

Calling a constructor of the parent class by mentioning the parent class name in the declaration
of the child class is known as sub-classing. A child class identifies its parent class by sub-
classing.

__init__( ) Function
The __init__() function is called every time a class is being used to make an object. When we
add the __init__() function in a parent class, the child class will no longer be able to inherit the
parent class’s __init__() function. The child’s class __init__() function overrides the parent
class’s __init__() function.

Python Certification Training Course

Explore Curriculum

1 class Parent:

2 def __init__(self , fname, fage):

self.firstname = fname
3
self.age = fage
4
def view(self):
5
print(self.firstname , self.age)
6
class Child(Parent):
7
def __init__(self , fname , fage):
8
9
Parent.__init__(self, fname, fage)
10
self.lastname = "edureka"
11
def view(self):
12 print("course name" , self.firstname ,"first came", self.age , " years ago
master python")
13
ob = Child("Python" , '28')
14
ob.view()
15

Types Of Inheritance
Depending upon the number of child and parent classes involved, there are four types of
inheritance in python.

Single Inheritance
When a child class inherits only a single parent class.

1 class Parent:

2 def func1(self):

print("this is function one")


3
class Child(Parent):
4
def func2(self):
5
print(" this is function 2 ")
6
ob = Child()
7
ob.func1()
8
ob.func2()
9

Multiple Inheritance
When a child class inherits from more than one parent class.

1
class Parent:
2
def func1(self):
3
print("this is function 1")
4 class Parent2:

5 def func2(self):

6 print("this is function 2")

7 class Child(Parent , Parent2):

8 def func3(self):

print("this is function 3")


9

10
ob = Child()
11
ob.func1()
12
ob.func2()
13
ob.func3()
14

Multilevel Inheritance
When a child class becomes a parent class for another child class.

1 class Parent:

2 def func1(self):

print("this is function 1")


3
4
class Child(Parent):
5 def func2(self):

6 print("this is function 2")

7 class Child2(Child):

8 def func3("this is function 3")

9 ob = Child2()

ob.func1()
10
ob.func2()
11
ob.func3()
12

Hierarchical Inheritance
Hierarchical inheritance involves multiple inheritance from the same base or parent class.

1 class Parent:

2 def func1(self):

print("this is function 1")


3
class Child(Parent):
4
def func2(self):
5
print("this is function 2")
6
class Child2(Parent):
7
def func3(self):
8
print("this is function 3")
9

10 ob = Child()

11 ob1 = Child2()

12 ob.func1()
13
ob.func2()
14

Hybrid Inheritance
Hybrid inheritance involves multiple inheritance taking place in a single program.

1
class Parent:
2
def func1(self):
3
print("this is function one")
4

5
class Child(Parent):
6 def func2(self):

7 print("this is function 2")

9 class Child1(Parent):

10 def func3(self):

11 print(" this is function 3"):

12
class Child3(Parent , Child1):
13
def func4(self):
14
print(" this is function 4")
15

16
ob = Child3()
17
ob.func1()
18

Python Super() Function


Super function allows us to call a method from the parent class.

1 class Parent:
2
def func1(self):
3
print("this is function 1")
4
class Child(Parent):
5
def func2(self):
6
Super().func1()
7
print("this is function 2")
8

9
ob = Child()
10 ob.func2()

Python Method Overriding


Method Overriding

You can override a method in python. Look at the example below.

1
class Parent:
2 def func1(self):

3 print("this is parent function")

5 class Child(Parent):

6 def func1(self):

7 print("this is child function")

8
ob = Child()
9
ob.func1()
10

The functionality of the parent class method is changes by overriding the same method in the
child class.
Inheritance is one of the most important concept of OOP. It provides code reusability, readability
and transition of properties which helps in optimized and efficient code building. Python
programming language is loaded with concepts like inheritance. Enormous python applications
calls for increased number of python programmers in the recent market..

Lab practical of unit-4: date:12/10/2021


Program1:--build a class simple program in python:
Generally speaking, instance variables are for data unique to each instance and class
variables are for attributes and methods shared by all instances of the class:

class Dog:

kind = 'canine' # class variable shared by all


instances

def __init__(self, name):


self.name = name # instance variable unique to each
instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'

As discussed in A Word About Names and Objects, shared data can have possibly
surprising effects with involving mutable objects such as lists and dictionaries. For
example, the tricks list in the following code should not be used as a class variable
because just a single list would be shared by all Dog instances:

Program2: simple program of inheritance in python:

1 class Parent:
2
def __init__(self , fname, fage):
3
self.firstname = fname
4
self.age = fage
5
def view(self):
6
print(self.firstname , self.age)
7
class Child(Parent):
8 def __init__(self , fname , fage):

9 Parent.__init__(self, fname, fage)

10 self.lastname = "edureka"

11 def view(self):

12 print("course name" , self.firstname ,"first came", self.age , " years ago." , self.las
master python")
13
ob = Child("Python" , '28')
14 ob.view()

15

For inheritance help by this link: https://www.edureka.co/blog/inheritance-in-python/

Inheritance program running process:-


End unit-4

Unit-5 26/10/2021
What is Python file handling?
Python too supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files. ... Python
treats file differently as text or binary and this is important. Each line of code includes a
sequence of characters and they form text file.
File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting
files.

File Handling
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not
exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax
To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

The code above is the same as:


f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need
to specify them.

Open a File on the Server


Assume we have the following file, located in the same folder as Python:

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading
the content of the file:

Example
f = open("demofile.txt", "r")
print(f.read())

Run Example »

If the file is located in a different location, you will have to specify the file path,
like this:

Example
Open a file on a different location:

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

Run Example »
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify
how many characters you want to return:

Example
Return the 5 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(5))

Run Example »

Read Lines
You can return one line by using the readline() method:

Example
Read one line of the file:

f = open("demofile.txt", "r")
print(f.readline())

Run Example »

By calling readline() two times, you can read the two first lines:

Example
Read two lines of the file:

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Run Example »

By looping through the lines of the file, you can read the whole file, line by line:

Example
Loop through the file line by line:

f = open("demofile.txt", "r")
for x in f:
print(x)

Run Example »

Close Files
It is a good practice to always close the file when you are done with it.

Example
Close the file when you are finish with it:

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Run Example »

Example
Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Run Example »

Note: the "w" method will overwrite the entire file.

Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")

Result: a new empty file is created!

Example
Create a new file if it does not exist:

f = open("myfile.txt", "w")

Delete a File
To delete a file, you must import the OS module, and run
its os.remove() function:

Example
Remove the file "demofile.txt":

import os
os.remove("demofile.txt")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you
try to delete it:

Example
Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:

Example
Remove the folder "myfolder":

import os
os.rmdir("myfolder")

What are command line arguments in Python? Date:28/10/2021


Python Command line arguments are input parameters passed to the script when
executing them. Almost all programming language provide support for command line
arguments. Then we also have command line options to set some specific options for
the program.

Adding the capability of processing Python command line arguments provides a user-
friendly interface to your text-based command line program. It’s similar to what a
graphical user interface is for a visual application that’s manipulated by graphical
elements or widgets.

Python exposes a mechanism to capture and extract your Python command line
arguments. These values can be used to modify the behavior of a program. For
example, if your program processes data read from a file, then you can pass the name
of the file to your program, rather than hard-coding the value in your source code.

Errors and exception handling:--


Errors are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal events occur
which changes the normal flow of the program. Two types of Error occurs in python.
Errors and Exceptions in Python
Errors are the problems in a program due to which the program will stop the execution.
On the other hand, exceptions are raised when some internal events occur which changes
the normal flow of the program.
Two types of Error occurs in python.

1. Syntax errors
2. Logical errors (Exceptions)

Syntax errors
When the proper syntax of the language is not followed then a syntax error is thrown.
Example

 Python3

# initialize the amount variable

amount = 10000

# check that You are eligible to

# purchase Dsa Self Paced or not

if(amount>2999)

print("You are eligible to purchase


Dsa Self Paced")
Output:

It returns a syntax error message because after the if statement a colon: is missing. We
can fix this by writing the correct syntax.

logical errors(Exception)
When in the runtime an error that occurs after passing the syntax test is called exception
or logical type. For example, when we divide any number by zero then the
ZeroDivisionError exception is raised, or when we import a module that does not exist
then ImportError is raised.
Example 1:

 Python3

# initialize the amount variable

marks = 10000

# perform division with 0

a = marks / 0

print(a)

Output:
In the above example the ZeroDivisionError as we are trying to divide a number by 0.
Example 2: When indentation is not correct.

 Python3

if(a<3):

print("gfg")

Output:

Some of the common built-in exceptions are other than above mention exceptions are:

Exception Description

IndexError When the wrong index of a list is retrieved.

AssertionError It occurs when the assert statement fails


Exception Description

AttributeError It occurs when an attribute assignment is failed.

ImportError It occurs when an imported module is not found.

KeyError It occurs when the key of the dictionary is not found.

NameError It occurs when the variable is not defined.

MemoryError It occurs when a program runs out of memory.

TypeError It occurs when a function and operation are applied in an incorrect type.

Note: For more information, refer to Built-in Exceptions in Python

Error Handling
When an error and an exception are raised then we handle that with the help of the
Handling method.

 Handling Exceptions with Try/Except/Finally


We can handle errors by the Try/Except/Finally method. we write unsafe code in the
try, fall back code in except and final code in finally block.
Example

 Python3

# put unsafe operation in try block

try:
print("code start")

# unsafe operation perform

print(1 / 0)

# if error occur the it goes in except


block

except:

print("an error occurs")

# final code in finally block

finally:

print("GeeksForGeeks")

 Output:

code start
an error occurs
GeeksForGeeks

 Raising exceptions for a predefined condition
When we want to code for the limitation of certain conditions then we can raise an
exception.
Example
 Python3

# try for unsafe code

try:

amount = 1999

if amount < 2999:

# raise the ValueError

raise ValueError("please add money


in your account")

else:

print("You are eligible to


purchase DSA Self Paced course")

# if false then raise the value error

except ValueError as e:

print(e)

 Output:

please add money in your account

Packages in Python
Introduction
We learned that modules are files containing Python statements and definitions, like
function and class definitions. We will learn in this chapter how to bundle multiple modules
together to form a package.

A package is basically a directory with Python files and a file with the name __init__.py.
This means that every directory inside of the Python path, which contains a file
named __init__.py, will be treated as a package by Python. It's possible to put several
modules into a Package.

Packages are a way of structuring Python’s module namespace by using "dotted module
names". A.B stands for a submodule named B in a package named A. Two different
packages like P1 and P2 can both have modules with the same name, let's say A, for
example. The submodule A of the package P1 and the submodule A of the package P2 can
be totally different. A package is imported like a "normal" module. We will start this chapter
with a simple example.

We will demonstrate with a very simple example how to create a package with some Python
modules. First of all, we need a directory. The name of this directory will be the name of the
package, which we want to create. We will call our package "simple_package". This
directory needs to contain a file with the name __init__.py. This file can be empty, or it
can contain valid Python code. This code will be executed when a package is imported, so it
can be used to initialize a package, e.g. to make sure that some other modules are
imported or some values set. Now we can put all of the Python files which will be the
submodules of our module into this directory. We create two simple files a.py and b.py just
for the sake of filling the package with modules.

The content of a.py:


def bar():
print("Hello, function 'bar' from module 'a' calling")

The content of b.py:


def foo():
print("Hello, function 'foo' from module 'b' calling")

We will also add an empty file with the name __init__.py inside of simple_package
directory.

Let's see what happens, when we import simple_package from the interactive Python shell,
assuming that the directory simple_package is either in the directory from which you call
the shell or that it is contained in the search path or environment variable "PYTHONPATH"
(from your operating system):
import simple_package
simple_package/a
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-347df8a711cc> in <module>
----> 1 simple_package/a

NameError: name 'a' is not defined


simple_package/b
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-e71d2904d2bd> in <module>
----> 1 simple_package/b

NameError: name 'b' is not defined

We can see that the package simple_package has been loaded but neither the module "a"
nor the module "b"! We can import the modules a and b in the following way:
from simple_package import a, b
a.bar()
b.foo()
Hello, function 'bar' from module 'a' calling
Hello, function 'foo' from module 'b' calling
As we have seen at the beginning of the chapter, we can't access neither "a" nor "b" by
solely importing simple_package.

Yet, there is a way to automatically load these modules. We can use the file __init__.py for
this purpose. All we have to do is add the following lines to the so far empty
file __init__.py:

import simple_package.a

import simple_package.b

It will work now:


import simple_package
simple_package.a.bar()
simple_package.b.foo()
Hello, function 'bar' from module 'a' calling
Hello, function 'foo' from module 'b' calling

Program: 1.. w a.p.word count 2..copy file

You might also like