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

Python Notes

Python is a high-level, interpreted, interactive, and object-oriented programming language known for its readability and ease of learning. Developed by Guido van Rossum, Python supports multiple programming paradigms and has a wide range of applications from web development to data science. Its features include a broad standard library, portability, and extensive community support, making it popular among developers and organizations.

Uploaded by

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

Python Notes

Python is a high-level, interpreted, interactive, and object-oriented programming language known for its readability and ease of learning. Developed by Guido van Rossum, Python supports multiple programming paradigms and has a wide range of applications from web development to data science. Its features include a broad standard library, portability, and extensive community support, making it popular among developers and organizations.

Uploaded by

iminfinity888
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

1

PYTHON NOTES
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 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.

• History of Python
• Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer
Science in the Netherlands.
• Python is derived from many other languages, including ABC, Modula-3, C,
C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now available under
the GNU General Public License (GPL).
• Python is now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing its progress.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


2

Python Features
Python's features include −
• 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.
Apart from the above-mentioned features, Python has a big list of good features,
few are listed below −
• 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.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


3

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

• Python Language advantages and applications


• Python is a high level, interpreted and general purpose dynamic programming
language that focuses on code readability.It has fewer steps when compared to
Java and C.It was founded in 1991 by developer Guido Van Rossum.It is used in
many organizations as it supports multiple programming paradigms.It also
performs automatic memory management.

Advantages :
1) Presence of third-party modules
2) Extensive support libraries(NumPy for numerical calculations, Pandas for data
analytics etc)
3) Open source and community development
4) Easy to learn
5) User-friendly data structures
6) High-level language
7) Dynamically typed language(No need to mention data type based on value
assigned, it takes data type)
8) Object-oriented language
9) Portable and Interactive
10) Portable across Operating systems
• Applications :
1) GUI based desktop applications(Games, Scientific Applications)
2) Web frameworks and applications
3) Enterprise and Business applications
4) Operating Systems
5) Language Development
6) Prototyping
• Organizations using Python :
1) Google(Components of Google spider and Search Engine)
2) Yahoo(Maps)
3) YouTube
4) Mozilla
5) Dropbox
6) Microsoft
7) Cisco
8) Spotify
9) Quora

NOTES BY SHRI JAYANT POHANE SIR 9373106604


4

Advantages/Benefits of Python
The diverse application of the Python language is a result of the
combination of features which give this language an edge over others.
Some of the benefits of programming in Python include:

1. Presence of Third Party Modules:

The Python Package Index (PyPI) contains numerous third-party


modules that make Python capable of interacting with most of the
other languages and platforms.

2. Extensive Support Libraries:

Python provides a large standard library which includes areas like


internet protocols, string operations, web services tools and operating
system interfaces. Many high use programming tasks have already
been scripted into the standard library which reduces length of code to
be written significantly.

3. Open Source and Community Development:

Python language is developed under an OSI-approved open source


license, which makes it free to use and distribute, including for
commercial purposes.

Further, its development is driven by the community which


collaborates for its code through hosting conferences and mailing lists,
and provides for its numerous modules.

4. Learning Ease and Support Available:

Python offers excellent readability and uncluttered simple-to-learn


syntax which helps beginners to utilize this programming language.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


5

The code style guidelines, PEP 8, provide a set of rules to facilitate the
formatting of code. Additionally, the wide base of users and active
developers has resulted in a rich internet resource bank to encourage
development and the continued adoption of the language.

5. User-friendly Data Structures:

Python has built-in list and dictionary data structures which can be
used to construct fast runtime data structures. Further, Python also
provides the option of dynamic high-level data typing which reduces
the length of support code that is needed.

6. Productivity and Speed:

Python has clean object-oriented design, provides enhanced process


control capabilities, and possesses strong integration and text
processing capabilities and its own unit testing framework, all of which
contribute to the increase in its speed and productivity. Python is
considered a viable option for building complex multi-protocol network
applications.

Comparing Python to Other


Languages
Java
Python programs are generally expected to run slower than Java programs, but they also
take much less time to develop. Python programs are typically 3-5 times shorter than
equivalent Java programs. This difference can be attributed to Python's built-in high-level
data types and its dynamic typing. For example, a Python programmer wastes no time
declaring the types of arguments or variables, and Python's powerful polymorphic list and
dictionary types, for which rich syntactic support is built straight into the language, find a use
in almost every Python program. Because of the run-time typing, Python's run time must
work harder than Java's. For example, when evaluating the expression a+b, it must first
inspect the objects a and b to find out their type, which is not known at compile time. It then
invokes the appropriate addition operation, which may be an overloaded user-defined
method. Java, on the other hand, can perform an efficient integer or floating point addition,

NOTES BY SHRI JAYANT POHANE SIR 9373106604


6

but requires variable declarations for a and b, and does not allow overloading of the +
operator for instances of user-defined classes.

For these reasons, Python is much better suited as a "glue" language, while Java is better
characterized as a low-level implementation language. In fact, the two together make an
excellent combination. Components can be developed in Java and combined to form
applications in Python; Python can also be used to prototype components until their design
can be "hardened" in a Java implementation. To support this type of development, a Python
implementation written in Java is under development, which allows calling Python code from
Java and vice versa. In this implementation, Python source code is translated to Java
bytecode (with help from a run-time library to support Python's dynamic semantics).

C++
Almost everything said for Java also applies for C++, just more so: where Python code is
typically 3-5 times shorter than equivalent Java code, it is often 5-10 times shorter than
equivalent C++ code! Anecdotal evidence suggests that one Python programmer can finish
in two months what two C++ programmers can't complete in a year. Python shines as a
glue language, used to combine components written in C++.

Disadvantages of Python
Python is a widely used general-purpose, high-level programming language. It is widely
used by developers in various domain like from web-development to Machine Learning.
Though, Python got its own set of advantages and disadvantages. Let’ see some of the
disadvantages of Python.
Speed: Python is interpreted language and is slow as compared to C/C++ or Java.
Unlike C or C++ it’s not closer to hardware because Python is a high-level language. As
we all know that compilation and execution help to work normally, but in this case,
execution of Python takes place with the help of an interpreter instead of the compiler
as we have seen that Python code is executed line by line, which causes it to slow
down. Speed is a focal point for the project required by any programmer. On the other
hand, it can be seen that it is fast for many web applications too.
Mobile Development: However Python is strong in desktop and server platforms, that
is it is an excellent server-side language but for the mobile development, Python is not a
very good language which means it is a weak language for mobile development. It is
very rarely used for mobile development. This is the reason very few mobile
applications are built in it like Carbonnelle, which is built in python.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


7

Below are the major features and applications due to which people choose
Python as their first programming language:

1. Python’s popularity & high salary


2. Python is used in Data Science
3. Python’s scripting & automation
4. Python used with Big Data
5. Python supports Testing
6. Computer Graphics in Python
7. Python used in Artificial Intelligence
8. Python in Web Development
9. Python is portable & extensible
10. Python is simple & easy to learn

10. Simple & Easy To Learn


So at number 10, Python is extremely simple and easy to learn. It is a very powerful
language and it closely resembles the English language!
So, what contributes to its simplicity? Python is

 Free & open source


 High-level
 Interpreted
 Blessed with large community

9. Portable & Extensible


The portable and extensible properties of Python allow you to perform cross-language
operations seamlessly. Python is supported by most platforms present in the industry
today ranging from Windows to Linux to Macintosh, Solaris, Play station, among others.

Python’s extensibility features allow you to integrate Java as well as .NET components.
You can also invoke C and C++ libraries.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


8

8. Web Development

Python has an array of frameworks for


developing websites. The popular frameworks are Django, Flask, Pylons etc. Since
these frameworks are written in Python, its the core reason which makes the code a lot
faster and stable.

You can also perform web scraping where you can fetch details from any other
websites. You will also be impressed as many websites such as Instagram, bit bucket,
Pinterest are build on these frameworks only.

7. Artificial Intelligence

AI is the next huge development in the tech


world. You can actually make a machine mimic the human brain which has the power to
think, analyze and make decisions.
Furthermore, libraries such as Keras and TensorFlow bring machine learning
functionality into the mix. It gives the ability to learn without being explicitly
programmed. Also, we have libraries such as openCv that helps computer vision or
image recognition.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


9

6. Computer Graphics

Python is largely used in small, large, online


or offline projects. It is used to build GUI and desktop applications. It uses ‘Tkinter‘
library to provide fast & easy way to create applications.

It is also used in game development where you can write the logic of using a module
‘pygame’ which also runs on android devices.

5. Testing Framework

Python is great for validating ideas or


products for established companies. Python has many built-in testing frameworks that
covers debugging & fastest workflows. There are a lot of tools and modules to make
things easier such as Selenium and Splinter.
It supports testing with cross-platform & cross-browser with frameworks such
as PyTest and Robot Framework. Testing is a tedious task and Python is the booster for
it, so every tester should definitely go for it!

NOTES BY SHRI JAYANT POHANE SIR 9373106604


10

4. Big Data

Python handles a lot of hassles of data. It supports


parallel computing where you can use Python for Hadoop as well. In Python, you have a
library called “Pydoop” and you can write a MapReduce program in Python and process
data present in the HDFS cluster.

There are other libraries such as ‘Dask‘ and ‘Pyspark‘ for big data
processing. Therefore, Python is widely used for Big Data where you can easily process
it!

3. Scripting & Automation


Many people only knows that Python is a programming language, but Python can also
be used as Scripting language. In scripting:

 The code is written in the form of scripts and get executed


 Machine reads and interprets the code
 Error checking is done during Runtime

Once the code is checked, it can be used several times. So by automation, you can
automate certain tasks in a program.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


11

2. Data Science

Python is the leading language of many data


scientist. For years, academic scholars and private researchers were using the
MATLAB language for scientific research but it all started to change with the release of
Python numerical engines such as ‘Numpy’ and ‘Pandas’.

Python also deals with the tabular, matrix as well as statistical data and it even
visualizes it with popular libraries such as ‘Matplotlib’ and ‘Seaborn‘.

1. Python’s Popularity & High Salary


Python engineers have some of the highest salaries in the industry. The average
Python Developer salary in the United States is approximately $116,028 per year.

• Built-in Data Types


• In programming, data type is an important concept.
• Variables can store data of different types, and different
types can do different things.
• Python has the following data types built-in by default, in
these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset

NOTES BY SHRI JAYANT POHANE SIR 9373106604


12

Boolean Type: bool


Binary Types: bytes, bytearray,
memoryview

• Getting the Data Type
• You can get the data type of any object by using the type()
function:
• Example
• Print the data type of the variable x:
• x=5
• print(type(x))
• Setting the Data Type
• In Python, the data type is set when you assign a value to a
variable:
• Example Data Type Try it
x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", list


"cherry"]

x = ("apple", "banana", tuple

NOTES BY SHRI JAYANT POHANE SIR 9373106604


13

"cherry")

x = range(6) range

x = {"name" : "John", "age" : dict


36}

x = {"apple", "banana", set


"cherry"}

x = frozenset({"apple", frozenset
"banana", "cherry"})

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview
• Setting the Specific Data Type
• If you want to specify the data type, you can use the
following constructor functions:
• Example Data Type Try it
x = str("Hello World") str

x = int(20) int

NOTES BY SHRI JAYANT POHANE SIR 9373106604


14

x = float(20.5) float

x = complex(1j) complex

x = list(("apple", "banana", list


"cherry"))

x = tuple(("apple", "banana", tuple


"cherry"))

x = range(6) range

x = dict(name="John", dict
age=36)

x = set(("apple", "banana", set


"cherry"))

x = frozenset(("apple", frozenset
"banana", "cherry"))

x = bool(5) bool

x = bytes(5) bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

NOTES BY SHRI JAYANT POHANE SIR 9373106604


15


• Python Casting
• x = int(1) # x will be 1
• y = int(2.8) # y will be 2
• z = int("3") # z will be 3

Creating Variables
Variables are containers for storing data values.
Unlike other programming languages, Python has no command for declaring a
variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)

Variable Names
• A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables: A variable name
must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
• Assign Value to Multiple Variables
• Python allows you to assign values to multiple variables in one line:

NOTES BY SHRI JAYANT POHANE SIR 9373106604


16


• Example
• x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

• Python Arithmetic Operators


• Arithmetic operators are used with numeric values to perform common
mathematical operations:
Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

NOTES BY SHRI JAYANT POHANE SIR 9373106604


17

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators


Assignment operators are used to assign values to variables:

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

NOTES BY SHRI JAYANT POHANE SIR 9373106604


18

Python Comparison Operators


Comparison operators are used to compare two values:

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Logical Operators


Logical operators are used to combine conditional statements:

Returns True if one of the


or x < 5 or x < 4
statements is true

Reverse the result, returns False


not not(x < 5 and x < 10)
if the result is true

NOTES BY SHRI JAYANT POHANE SIR 9373106604


19

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
Operator Description Example
is Returns true if both x is y
variables are the same
object
is not Returns true if both x is not y
variables are not the
same object

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a x in y
sequence with the
specified value is present
in the object
not in Returns True if a x not in y
sequence with the
specified value is not
present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

NOTES BY SHRI JAYANT POHANE SIR 9373106604


20

Operator Name Description


& AND Sets each bit to 1 if both
bits are 1
| OR Sets each bit to 1 if one
of two bits is 1
^ XOR Sets each bit to 1 if only
one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing
zeros in from the right
and let the leftmost bits
fall off
>> Signed right shift Shift right by pushing
copies of the leftmost bit
in from the left, and let
the rightmost bits fall off

Python If ... Else


Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements"
and loops.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


21

NOTES BY SHRI JAYANT POHANE SIR 9373106604


22

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object-orientated programming
languages.
With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.
fruits = ["apple", "banana",
"cherry"]
for x in fruits:
print(x)
apple
banana
cherry

NOTES BY SHRI JAYANT POHANE SIR 9373106604


23

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


for x in fruits:
print(x)
if x == "banana":
break

apple
banana

for x in range(6):
print(x)
0
1
2
3
4
5

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


for x in fruits:
if x == "banana":
continue
print(x)

apple
cherry

NOTES BY SHRI JAYANT POHANE SIR 9373106604


24

for x in range(2, 30, 3):


print(x)

2
5
8
11
14
17
20
23
26
29

adj = ["red", "big", "tasty"]


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

for x in adj:
for y in fruits:
print(x, y)

red apple
red banana
red cherry
big apple
big banana
big cherry

NOTES BY SHRI JAYANT POHANE SIR 9373106604


25

tasty apple
tasty banana
tasty cherry

The while Loop


With the while loop we can execute a set of statements as long as a condition is
true.

#Print i as long as i is less than 6:


i=1
while i < 6:
print(i)
i += 1
1
2
3
4
5

Python break statement


The break statement terminates the loop containing it. Control of the program
flows to the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


26

Python continue statement


The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1
2
3

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

1
2
4
5
6

NOTES BY SHRI JAYANT POHANE SIR 9373106604


27

Using nested loops


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!")


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

NOTES BY SHRI JAYANT POHANE SIR 9373106604


28

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!

NOTES BY SHRI JAYANT POHANE SIR 9373106604


29

USING NESTED FOR


for i in range(1,6):
for j in range(i):
print("*",end=' ')
print()

*
**
***
****
*****
Using break and continue
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
Current Letter : P
Current Letter : y
Current Letter : t

val in "string":
if val == "i":
continue
print(val)
print("The end")
g

NOTES BY SHRI JAYANT POHANE SIR 9373106604


30

The end
Python - pass Keyword
The pass keyword as name suggests, does nothing. It is used as
a dummy place holder whenever a syntactical requirement of a
certain programming element is to be fulfilled without
assigning any operation. In other words, the pass statement is
simply ignored by the Python interpreter and can be seen as a
null statement. It is generally used as a dummy statement in a
code block, for example in the if or else block.
for num in range(1,6):
if num==3:
pass
else:
print (num)
1
2
4
5
String Literals
String literals in python are surrounded by either single
quotation marks, or double quotation marks.
'hello' is the same as "hello".
print("Hello")
print('Hello')

NOTES BY SHRI JAYANT POHANE SIR 9373106604


31

a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three
quotes:
a = """NAVIN
JUNEJA
BCCA."""
print(a)

Strings are Arrays


Like many other popular programming languages, strings in
Python 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.
a="hello advance"
print(a[1])

NOTES BY SHRI JAYANT POHANE SIR 9373106604


32

Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon,
to return a part of the string.
b="hello world"
print(b[2:5])

llo

b="hello world"
print(b[-5:-2])
wor
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
a="navin"
print(len(a))
5
The strip() method removes any whitespace from the beginning
or the end:
a=" Hello, World! "
print(a.strip())

NOTES BY SHRI JAYANT POHANE SIR 9373106604


33

a = "Hello, World!"
print(a.lower())
a = "Hello, World!"
print(a.upper())

a = "Hello, World!"
print(a.replace("H", "J"))

a = "Hello, World!"
print(a.split(","))
['Hello', ' World!']
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming
language:
• List is a collection which is ordered and changeable. Allows
duplicate members.
• Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


34

• Set is a collection which is unordered and unindexed. No


duplicate members.
• Dictionary is a collection which is unordered, changeable
and indexed. No duplicate members.
When choosing a collection type, it is useful to understand the
properties of that type. Choosing the right type for a particular
data set could mean retention of meaning, and, it could mean
an increase in efficiency or security.
List
A list is a collection which is ordered and changeable. In Python
lists are written with square brackets.
thislist=["banana","apple","cherry"]
print(thislist)
['banana', 'apple', 'cherry']
Access Items
You access the list items by referring to the index number:

thislist=["banana","apple","cherry"]
print(thislist[1])
apple

thislist=["banana","apple","cherry"]
print(thislist[-1])

NOTES BY SHRI JAYANT POHANE SIR 9373106604


35

cherry

list1=["a","b","c"]
list2=[1,2,3]
list3=list1+list2
print(list3)

['a', 'b', 'c', 1, 2, 3]


thislist=["apple","banana","orange","melon","pinappl
e"]
print(thislist[2:5])
['orange', 'melon', 'pinapple']

thislist=["apple","banana","cherry"]
for x in thislist:
print(x)
apple
banana
cherry

list1=["a","b","c"]
list2=[1,2,3]
for x in list2:
list1.append(x)
print(list1)
['a', 'b', 'c', 1]
['a', 'b', 'c', 1, 2]
['a', 'b', 'c', 1, 2, 3]

NOTES BY SHRI JAYANT POHANE SIR 9373106604


36

Or you can use the extend() method, which purpose is to add


elements from one list to another list

list1=["a","b","c"]
list2=[1,2,3]
list1.extend(list2)
print(list1)
['a', 'b', 'c', 1, 2, 3]

list1=["a","b","c"]
list2=list1.copy()
print(list1)
print(list2)
['a', 'b', 'c']
['a', 'b', 'c']

Tuple
A tuple is a collection which is ordered and unchangeable. In
Python tuples are written with round brackets.

thistuple=("apple","banana","cherry")
print(thistuple)
('apple', 'banana', 'cherry')

NOTES BY SHRI JAYANT POHANE SIR 9373106604


37

Repeat same example of List only change is that replace [ ] with


( ).

Dictionary
A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets,
and they have keys and values.
thisdict={
"brand":"ford",
"model":"mustang",
"year":1964
}
print(thisdict)

{'brand': 'ford', 'model': 'mustang', 'year': 1964}

thisdict={
"brand":"ford",
"model":"mustang",
"year":1964
}
thisdict["year"] = 2018

print(thisdict)

{'brand': 'ford', 'model': 'mustang', 'year': 2018}

NOTES BY SHRI JAYANT POHANE SIR 9373106604


38

thisdict={
"brand":"ford",
"model":"mustang",
"year":1964
}
for x in thisdict:
print(thisdict)

{'brand': 'ford', 'model': 'mustang', 'year': 1964}


{'brand': 'ford', 'model': 'mustang', 'year': 1964}
{'brand': 'ford', 'model': 'mustang', 'year': 1964}

Python Functions

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.

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

NOTES BY SHRI JAYANT POHANE SIR 9373106604


39

my_function()

Hello from a function

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

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

Emil Refsnes
Tobias Refsnes
Linus Refsnes
def my_function(country = "Norway"):
print("I am from " + country)

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

I am from Sweden
I am from India
I am from Norway
I am from Brazil
def my_function(food):
for x in food:
print(x)

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

my_function(fruits)

apple
banana
cherry

NOTES BY SHRI JAYANT POHANE SIR 9373106604


40

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

def my_function(*kids):
print("The youngest child is " + kids[2])

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


The youngest child is Linus

In Python, anonymous function is a function that is defined


without a name. While normal functions are defined using
the def keyword, in Python anonymous functions are defined
using the lambda keyword. Hence, anonymous functions are
also called lambda functions.
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can
only have one expression.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


41

x = lambda a : a + 10
print(x(5))
A lambda function that sums argument a, b, and c and print the
result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an
anonymous function inside another function.
Say you have a function definition that takes one argument,
and that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

These terms of global and local correspond to a variable's reach


within a script or program. A global variable is one that can be
accessed anywhere. A local variable is the opposite, it can only
be accessed within its frame. The difference is that global
variables can be accessed locally, but not modified locally
inherently.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


42

A local variable cannot be accessed globally, inherently. Now,


dont worry about committing that to memory right now, I think
it makes a lot more sense when you just see and do it, so let's
do that.
x=6
def example():
print(x)
# z, however, is a local variable.
z=5
# this works
print(z)
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.
To create a module just save the code you want in a file with
the file extension .py:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Now we can use the module we just created, by using the
import statement:

NOTES BY SHRI JAYANT POHANE SIR 9373106604


43

import mymodule
mymodule.greeting("Jonathan")
Variables in Module
The module can contain functions, as already described, but
also variables of all types (arrays, dictionaries, objects etc):
Import the module named mymodule, and access the person1
dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)

Create an alias for mymodule called mx:


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

Import and use the platform module:


import platform
x = platform.system()
print(x)

NOTES BY SHRI JAYANT POHANE SIR 9373106604


44

Python - Math Module


Some of the most popular mathematical functions are defined
in the math module. These include trigonometric functions,
representation functions, logarithmic functions, angle
conversion functions, etc. In addition, two mathematical
constants are also defined in this module.
Pie (π) is a well-known mathematical constant, which is defined
as the ratio of the circumference to the diameter of a circle and
its value is 3.141592653589793
>>> import math
>>>math.pi
3.141592653589793
The math module contains functions for calculating various
trigonometric ratios for a given angle. The functions (sin, cos,
tan, etc.) need the angle in radians as an argument. We, on the
other hand, are used to express the angle in degrees. The math
module presents two angle conversion functions: degrees() and
radians(), to convert the angle from degrees to radians and vice
versa. For example, the following statements convert the angle
of 30 degrees to radians and back (Note: π radians is equivalent
to 180 degrees).
>>>math.radians(30)
0.5235987755982988
>>>math.degrees(math.pi/6)

NOTES BY SHRI JAYANT POHANE SIR 9373106604


45

29.999999999999996
The following statements show sin, cos and tan ratios for the
angle of 30 degrees (0.5235987755982988 radians):
>>math.sin(0.5235987755982988)
0.49999999999999994
>>>math.cos(0.5235987755982988)
0.8660254037844387
>>>math.tan(0.5235987755982988)
0.5773502691896257
math.log()
The math.log() method returns the natural logarithm of a given
number. The natural logarithm is calculated to the base e.
>>>math.log(10)
2.302585092994046
math.log10()
The math.log10() method returns the base-10 logarithm of the
given number. It is called the standard logarithm.
>>>math.log10(10)
1.0

NOTES BY SHRI JAYANT POHANE SIR 9373106604


46

math.pow()
The math.pow() method receives two float arguments, raises
the first to the second and returns the result. In other words,
pow(4,4) is equivalent to 4**4.
>>>math.pow(2,4)
16.0
>>>2**4
16
math.sqrt()
The math.sqrt() method returns the square root of a given
number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
The following two functions are called representation
functions. The ceil() function approximates the given number to
the smallest integer, greater than or equal to the given floating
point number. The floor() function returns the largest integer
less than or equal to the given number.
>>>math.ceil(4.5867)

NOTES BY SHRI JAYANT POHANE SIR 9373106604


47

5
>>>math.floor(4.5687)
4
What are packages?
We don't usually store all of our files in our computer in the
same location. We use a well-organized hierarchy of directories
for easier access.
Similar files are kept in the same directory, for example, we
may keep all the songs in the "music" directory. Analogous to
this, Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of
modules, we place similar modules in one package and
different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.
Similar, as a directory can contain sub-directories and files, a
Python package can have sub-packages and modules.
A directory must contain a file named __init__.py in order for
Python to consider it as a package. This file can be left empty
but we generally place the initialization code for that package in
this file.
Here is an example. Suppose we are developing a game, one
possible organization of packages and modules could be as
shown in the figure below.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


48

Python File Open


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.

NOTES BY SHRI JAYANT POHANE SIR 9373106604


49

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
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
f = open("demofile.txt", "r")
print(f.read())
f = open("demofile.txt", "r")
print(f.readline())
Write to an Existing File

NOTES BY SHRI JAYANT POHANE SIR 9373106604


50

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())
Python Exceptions
An exception can be defined as an abnormal condition in a
program resulting in the disruption in the flow of the program.
Whenever an exception occurs, the program halts the
execution, and thus the further code is not executed.
Therefore, an exception is the error which python script is
unable to tackle with.
Python provides us with the way to handle the Exception so
that the other part of the code can be executed without any
disruption. However, if we do not handle the exception, the

NOTES BY SHRI JAYANT POHANE SIR 9373106604


51

interpreter doesn't execute all the code that exists after the
that.
Common Exceptions
A list of common exceptions that can be thrown from a normal
python program is given below.
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local
or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)

#other code:
print("Hi I am other part of the program")
Enter a:10
Enter b:0

NOTES BY SHRI JAYANT POHANE SIR 9373106604


52

Traceback (most recent call last):


File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
else:
print("Hi I am else block")
Enter a:10
Enter b:2
a/b = 5
Hi I am else block

NOTES BY SHRI JAYANT POHANE SIR 9373106604


53

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Enter a:10
Enter b:0
can't divide by zero

NOTES BY SHRI JAYANT POHANE SIR 9373106604

You might also like