Python
Python
Python
Python Programming
From 16th July 2018 To 4th August 2018
BY : SU MANTA BISWAS
SBISWAS2007@G MAIL .C OM
09899720506
Session –I
Refreshing on Programming
Road Map and Session Plan
Q. Is it Programming Language ?
It is the high level programming language, which means that is separate the user from
the underlying operating system as much as possible.
Python is interpreted, which means that python code is translated and executed by an
interpreter one statement at a time.
In a compiled language, the entire source code is compiled and then executed
altogether.
Python is a general-purpose programming language
You can use Python to write code for any programming task.
Python is now used in the Google search engine, in mission critical projects at NASA
Transaction Processing at the New York Stock Exchange
Python is Object Oriented Programming (OOP)
Language
A class is essentially a type or category that defines objects of the same kind with
properties and methods for manipulating objects
Programme written in Python3 is not compatible with Python2. and not backward
compatible
Python provides a tool that automatically converts code written in Python2 into syntax
Python3 can use.
Companies Using Python
What you can do using Python?
Exercise: What we can do using Python
*ython, that is, these different flavors of python. Lets start understanding it
1. Cpython:
The base of all these implementation is Cpython or more formally known as python
(Yeah its True your Python is actually Cpython).
Cpython is de-facto reference Python implementation. Some implementations may
extend behavior or features in some aspects or re-implementations language that do
not depend or interact with the CPython runtime core but reuses the standard library
implementation of Cpython. Since Cpython is standard to implement python someone
can implement it to be compiled or to be interpreted according to their requirements.
It is written in C and is a bytecode interpreter. Your bytecode is executed on CPython
Virtual Machine. That is why I used to say foolishly that Python is interpreted language
which indirectly is True about Cpython not for all python variants.
2. Jython
Jython: Jython,earlier known as Jpython (or known to be successor of Jpython) is an
implementation of the Python programming language which is designed to run on the
Java Platform. It has compiler which compiles your python code into Java bytecode.
Stable releases of compatible python(latest) is still not available.
But question is why we need Jython?
Jython adds compatible libraries of python that are really helpful for developers(Now
you have both java and Python libraries at one place, isn’t that great?) and make it more
powerful language. You can look at this as a way to glue together and leverage an
existing collection of class libraries. Some find syntax of python concise and quicker.
For a instance you want to write HTTP GET request in java, how much code you have to
right? and when you know urllib in python isn’t things get easier?
3. Iron Python
IronPython: IronPython is another implementation of the Python targeting the .NET
Framework.
It is entirely written in C# and runs on .NET virtual machine(That is nothing but CLR).
Again you can import C# classes into ironPython. IronPython can use the .NET
Framework and Python libraries(again isn’t that great ), providing Python developers
with the power of the .NET framework or providing .NET developers with power of
scripting.
Current version targets Python 2.7.There are some known compatibility issues with
Cpython libraries.
4). Pypy
Pypy: Pypy is actually bit different than other implementations its primary focus is to
overcome drawbacks(so called) of python.
It is a Python interpreter and just-in-time compiler. It is written in Python itself. Actually
PyPy is written in a language called RPython, which is suitable for writing dynamic
language interpreters (and not much else). RPython is a subset of Python and is itself
written in Python. According to claims made by pypy its around 6 times faster than
Python.
While JIT is main goal, it also focuses on efficiency and compatibility with the original
CPython interpreter. Its implementation is highly compatible with Cpython.
There are many talks about pypy being the future of the languages. For some JIT may
not that useful for small scripts with non-repeatable code. Lets wait and watch for more
of Pypy, future is yet to come.
5. Stackless Python
Stackless Python: If you ever tried threading in python then you will understand what
and why Stackless Python. Stackless Python is a reimplementation of traditional python
and its key point is lightweight threading. You can say its branch of CPython supporting
microthreads.
Stackless python's key concept is tasklets which is nothing but tiny taks. It allows you to
run hundreds of thousands of tasklets in a single main thread. Tasklets run
independently on CPU and can communicate with other via Channels. Channel is sort of
manager that take all the responsibility to control suspension and resuming of tasklets.
You can also control scheduling of tasklets and not to mention serialization with pickle
can be done for tasklets.
Stackless is claimed to be completely compatible with Standard Python but some
issue been reported when using with PyQT.
6. ActiveState ActivePython:
Portable Python: How about having python language pre-configured, any time, any
where ,run directly from any USB storage device.
It is what Portable python is.
Its for Windows OS. You just need to extract it to your portable storage device.
9. Anaconda Python:
Anaconda Python: In short words you can say it is distribution for large-scale data
processing, predictive analytics, and scientific computing.
This implementation basically focuses large scale of data.
10. PyCharm
PyCharm is an integrated development environment (IDE) used in computer
programming, specifically for the Python language. It is developed by the Czech
company JetBrains.
It provides code analysis, a graphical debugger, an integrated unit tester, integration
with version control systems (VCSes), and supports web development with Django.
PyCharm is cross-platform, with Windows, macOS and Linux versions. The Community
Edition is released under the Apache License, and there is also Professional Edition
released under a proprietary license - this has extra features.
What are the Components of a Python Programme?
Q. Create a list and print the each element of the list with index number.
•The use of the compilation and byte code stages help to improve performance and
makes Python much faster than pure interpreter such as BASIC, but slower than the
truly complied languages such as C and PASCAL.
•However, unlike many other languages, the byte code versions of the modules can be
saved and executed without having to recompile them each time they are required ,
thereby improving performance by eliminating the compilation stage.
•Note that the byte code that is created is completely platform and operating system
independent , much like the byte code produced by Java.
Working of Python Program
Conclusion
You can enter Python statements interactively from the Python prompt >>>
Python Programs can be written on the script mode and commands can be executed
on the interactive mode.
Quick Recap
Comments ( Single and Multiple Lines)
Python Identifier
Q. How do you define or declare a variable?
Q. Declare a numeric variable
Q. Declare a string variable
Q. Check the type of both of the variable.
Q. What is the maximum numeric value you can store in a variable.
Reserved Keywords
Q. Write the code to find the reserved Keywords
Numbers
Strings
List
Dictionary
Tuple
File
Examples : Creating different Objects
>>>integer=12345
>>>float=123.45
>>> string=‘Hello’
>>>list=[1,2,’three’, ‘four’,100]
>>>dictionary={1: ‘one’, 2:’Two’, 3:’Three’, 4:’Four’}
>>>Tuple=(10,11,12, ,Thirteen)
Manipulation of Objects:
Hence, when we make changes in the original list, the copied list was unaffected by the
change
Using built-in function
Python has a built-in copy function which can be used to make copy of an existing
list.
In order to use the copy function, first we have to import it.
>>> from copy import copy #import library
>>>lst_original=[1,2,3,4]
>>>lst_copy=copy(lst_original)
Now append the original list and will find that there is no change in the copy list
.
Lists are Mutable
List are mutable
The value of any elements inside the list can be changed at any point of time.
The elements of the list are accessible with their index value
>>>list[3]=50
Traversing a List
Traversing a list means accessing all the elements or items of the list.
Traversing can be done by using any conditional statement of Python, but it is preferable to
use for loop.
Traversing in list is done in the same way as in string
Example:
The pop operator deletes the element on the provided index and stores that
element in a variable for further use.
Deleting Elements from a List
Del Operator: The del operator deletes the value on the provided index, but it does not
store the value for further use.
>>>del (lst_or[2])
remove Operator
Remove Operator: We use the remove operator if we know the item that we want to remove
or delete from the list( but not the index)
>>>list=[10,20,30]
>>>list.remove(10)
>>>print list
Note : In order to delete more than one value from a list, del operator with slicing is used
>>>list=[1,2,3,4,5,6,7]
>>>del list[1:3]
>>>print list
Built –in List Operators
1. Concatenation:
The concatenation operator works in lists in the same way it does in a string.
This is done by + operators
>>>list1= [10,20,30,40]
>>>list2=[50,60,70]
List3= list1+list2
Repetition
The repetition operator works as suggested by its name.
It repeats the list for a given number of times
>>>list=[1,2,3,4]
List*4
In-Operator
The in operator tells the user whether the given string exist in the list or not.
It gives a Boolean output. i.e True or false.
Example 1:
>>>list=[“Hello”, “Python”, “Program”]
>>> “Hello” in list
>>>”world” in list
Example2:
>>>list2=[10,20,30]
>>> 10 in list2
Built-In List Method
Sl. Method Description
1 cmp(list1,list2) It compares the elements of both the lists, list1 and list2
2 len(list) It return the length of the string, i.e the distance from
starting element to last element
3 max(list) It returns the item that has the maximum value in a list
4 min(list) It returns the item that has the minimum value in a list
The parentheses at the time of creating a tuple is not necessary, but it is good
practice to use parentheses.
Tuples can have any number of different data items( that is integer, float, list etc)
Tuples
In order to access the values in a tuple, it is necessary to use the index number enclosed
in square brackets along with the name of the tuple.
>>>tup[2]
>>>tup[4]
>>>tup[1:4]
>>>tup[:1]
>>>tup[0:]
6.1.3: Tuples are Immutable
Tuples are immutable.
The values or items in the tuple cannot be changed once it is declared.
If we want to change the values, we have to create a new tuple.
6.1.4: Tuple Assignment
It allows the assignment of values to a tuple of a variables on the left side of the
assignment from the tuple of values on the right side of the assignment
The number of variables in the tuple on the left of the assignment must match the
number of elements / items in the tuple on the right of the assignment.
# Creating a Tuple
>>>Anil=(‘221’, ‘Anil’,’Rahul’, ‘Delhi’, ‘1971’ , ‘Jaipur’)
#Tuple Assignment
>>>(id, f_name, l_name, city, yr_birth, brith_place)=Anil
Tuples as return Values
Tuples can also be returned by the function as return values
Generally, the function returns only one value but by returning tuple, a function can
return more than one value.
Example:
>>>def div_mod(a,b):
◦ Quot=a/b
◦ Remain=a%b
◦ Return Quot, remain #function returning two values
Basic Tuples Operations
1. Concatenation: This operator concatenates two tuples
This is done by + operator
>>>tup3=tup1+tup2
2. Repetition: It repeats the tuples in a given number of times
>>>tup * 5
3. In Operator
It tells the user that the given element exist in the tuple or not.
>>> tuple=(“Anil”, “Rahul”, “Rohan”)
>>> “Anil” in tuple
4. Iteration:
>>>for i in tup:
print i
Built in Tuple Functions
Sl.No Functions Description
1 cmp(tuple1, tuple2) It compares the items of two tuples
2 len(tuple) It returns the length of a tuple
3 zip(tuple1, tuple2) it zips elements from two tuples into a list of tuple
4 max(tuple) It returns the largest value among the elements in a
tuple
5 min(tuple) It returns the smallest value among the elements in a
tuple
6 tuple(seq) It converts a list into a tuple
Working with Sets
Introduction to sets
Empty Dictionary
>>>dict1={}
In order to access the elements from a dictionary, we can use the value of the key
enclosed in square brackets.
Python also provides a get() method that is used with the key in order to access
the value. print(dict1.get(3))
There is difference between the two.
Updating Dictionary
Dictionaries in Python are mutable. Unlike those in tuple and string., the value in a
dictionary can be changed, added or deleted.
If the key is present in the dictionary, then the associated value with the key is updated
or changed ; otherwise a new key: value pair is added
Adding new entries to a Existing Dict
To add new item to a dictionary you can use the subscript [] operator.
Syntax:
Dictionary_Name[key] = value
Example:
>>> D={'Virat Kohli':52,'Sachin':100}
>>> D
>>> type(D)
>>> D['Dhoni']=28 #Adding New value to D
>>> D
{'Sachin': 100, 'Dhoni': 28, 'Virat Kohli': 52}
Deleting Entries from Dictionaries
The del operator is used to remove the key and its associated value.
Syntax: del dictionary_name[key]
Example:
>>> D={'Virat Kohli':52,'Sachin':100, 'Dhoni': 28}
>>> D
{'Sachin': 100, 'Dhoni': 28, 'Virat Kohli': 52}
>>> del D['Dhoni'] #Deleting one entry
>>> D
{'Sachin': 100, 'Virat Kohli': 52}
Properties of Dictionary Keys
Prop-1: Duplicate keys are not allowed in the dictionary
Prop-2: Keys are immutable i.e, we can use string, integers or tuples for dictionary keys,
but something like [‘key’] is not valid as a key
The Methods of Dictionary Class
Sl.No Methods What it does? Example
Output: