Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

Python

Python is a general-purpose interpreted, interactive, object-oriented, and high-


level
programming language. It was created by Guido van Rossum during 1985 – 1990.

it is implemented based on diffrent language features like c,c++,java,shell


script,perl.

Python 3.0 was released in 2008 .

note: most of the people are calling python is a scripting language because the
way of developing python applications and execution of python applications are
similar to the scripting languages
all scripting languages are interpreted languages. Scripting is used automate
tasks (like shell scrpting).
In fact python is general-purpose programming language,but not scripting
language, but it supports scripting.
Features of Python:
Simple and easy to learn:
1)Python language systax is very simple. So programmer can focus on business
logic implemention rather than syntax
2)without having any programming language knowledge directly anybody cans
learn python language.
3) the simple and powerful sysntax of the python language makes the
programmer to express their business logic in less number lines of code, So
project development cost, time, maintenance cost will less
Python is Interpreted:
Python is processed at runtime by the interpreter. You do not need to compile
your program before executing it. When you execute a program, Python first
compiles your source code (the statements in your file) into a format known as
byte code. Compilation is simply a translation step, and byte code is a lower-
level, platform-independent representation of your source code. Byte code can be
run much more quickly than the original source code statements in your text file.
Byte code will be stored in a file with ‘.pyc’. Up to python 2.x this file created in
the same directory in with the source file is compiled. From python3.x this file is
created in __pychache__ folder in with the source file is compiled.

Source changes: Python automatically checks the last-modified timestamps of


source and byte code files to know whether it must be recompiled or not. If you
edit and resave your source code, byte code is automatically re-created the next
time your program is run.

An interpreter is a kind of program that executes other programs. It is a layer of


software logic between your code and the computer hardware on your machine. It
is available in executable form.

Platform Independent
Python is a platform independent language:
When the python program (ex: sample.py)is interpreted for the first time , first it is
compiled (i.e it checks all syntax errors). Once it is compiled successfully , .pyc
file(ex: sample.pyc) will be created. It contains source code instructions in the
form of byte code. It is independent of all the platforms. so it is portable.

Automatic Memory Management:


Python is garbage collected language. As python programmer we neet not focus
on memory de-allocation. it uses Garbage collector to de-allocate memory
automatically.
-Interactive:
Python has support for an interactive mode, which allows interactive testing and
debugging of snippets of code. i.e You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.

Extensible: it allows us to use the code which is implemented in other languages


like c,c++.
Embedded:
we can embed the python code into the other language programs such as c, c++,
java
In order to provide the scripting capabilities to the other language
programs/applications we use python code into those applications.
Some companies who using python are:
Google:
Many components of the Google spider and search engine are written in
Python)
Facebook:
Face book using python to get public data
--Yahoo Maps:
Yahoo mapping lookup services were implemented in Python
--Youtube:
Entire Youtube built on python django framework (except streaming).
--NASA.
--IBM.
--Mozilla.

--In Games we use python to implement core elements of the game play such as
score keeping and team balancing.
-- Python provides interfaces to all major commercial databases.
--python Supports OOP , Procedural programming, functional programing.
-- Python is open source software. So anybody can read python source code and
they can do the modifications in the python source code and they can re-
distribute that code to others.

By using python, we can develop following applications


1)GUI application development
2)web application development
3)Data Analysis
4)Task automations
5)Test Case implementations
6)Scientific application development
7)Network application development
8)Gaming/animation application development

Popular Python Flavors:


Cpython: it is default python. Most of companies using cpython for application
development . In cpython, python code is deployed into pvm(python virtual
machine) which is implemented in c language.

Jython(Jpython):
The jython system (originally known as JPython) is an alternative implementation
of the Python language, targeted for integration with the Java programming
language. Jython consists of Java classes that compile Python source code to
Java byte code and which is loaded into Java Virtual Machine (JVM).
Programmers still code Python statements in .py text files as usual.

Iron Python : it is designed to allow Python programs to integrate with


applications coded to work
with Microsoft’s .NET Framework for Windows, as well as the Mono open source
equivalent for Linux. .NET. It is implemented in c#.net

Anaconda python: I t is very powerful python than other flavors. It comes with
very huge number packages. it is distribution for large-scale data processing,
predictive analytics, and scientific computing. This implementation basically
focuses large scale of data. This distribution comes with django by default.

There are many other flavors like Stack less Python, Active Python...etc
There are two populer python web sites
1) www.python.org (it is used to download basic python).
2) www.continuum.lo (it is used to download anaconda python)
Even it is basic python or anaconda python, python code syntax will not be
changed.

Installation of python on windows:


 Download Python Windows x86-64 executable installer from this link
https://www.python.org/downloads/windows/
Click “Windows X86-64 executable installer”
Click on down-arrow link next to the downloaded file at bottom and select “Show
in folder” option;
Right-click the installer file labeled as “python-3.6.0-amd64.exe” and select “Run
as administrator” option;
click Yes to continue;
Check box “Add Python 3.6 to PATH” and click “Customize installation” to
continue;
Keep all options checked and press Next button to continue;
Enable check box labeled as “Install for all users” and enter “C:\python” in
“Customize install location”. Click “Install” button to continue;
In the next screen, click “Disable path length limit” and click “Close” button to
finish the installation procedure;

Installation of python on ubuntu:

1)Download Gzipped source tarball from Python's download URL:


https://www.python.org/ftp/python
2)Extract the tarball
tar xvfz Python-3.5.1.tgz
3)set the path of python home folder in bashrc file as follows
export PYTHON_HOME=\home\axness\work\python-3.6.2
export PATH=$PYTHON_HOME\bin:$PATH
or
simple way is
$sudo apt-get install python3-minimal

Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module
or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by
zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within
identifiers.

Naming conventions for Python identifiers


1)Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
2)Starting an identifier with a single leading underscore indicates that the
identifier
is private(so it is accessble within the module only. But not out side the module).
3)Starting an identifier with two leading underscores indicates a strong private
identifier(so it can be accessed with in the class only. But not from the outside
the class
4)If the identifier also ends with two trailing underscores, the identifier is a
language-
defined special name.

Lines and Indentation


Python does not use braces({}) to indicate blocks of code for class and function
definitions
or flow control. Blocks of code are denoted by line indentation, which is rigidly
enforced.
The number of spaces in the indentation is variable, but all statements within the
block
must be indented the same amount.

Development of python applications and programs:


we can develop python programms in two modes
1)inter active mode
2)barch mode or script mode

Interactive mode:
it is a commnad line shell. If we write any code at command line shell, it will be
executed immediately and gives result. It is used to test the features of the
python. It is not used to development of the large scale business applications.

To enter into python prompt, type python at $ prompt


$python
>>>#type python script to execute
EX:
>>> print('Hello world!')
Hello world!
>>> print(2 ** 8)
256
>>> import os
>>> os.getcwd()
o/p /home/axness/
Note : ‘os’ predefine module. os.getcwd() returns path of the current working
directory
Note : To come out from the python type either exit() method or CTRL+D in
ubuntu os. In case of windows , press CTRL+Z or type exit()

SCRIPT MODE :
In script mode we write group of python statements in any one of following
editors(IDE’S)

Different Editors :

1)Nano Editor
2)Gedit Editor
3)Vi editor
4)Eclipse IDE’S
5)Netbeans IDE’S
6)Pycharm IDE
Note: PyCharm IDE for professional developers. it is industry standard. All the
companies using pycharm for Python application development.

=>After writing the group of python statements in editor, we save the file with
extension “.py” or
“.pyw”.
=>After developing the .py (or) .pyw files we submit those files to the python
interpretor directly.
=>Batch mode is used for large scale application development,

Step 1:
open gedit and type following code

# A first Python script


import sys # Load a library module
print(sys.platform) #print type of working os . sys is standard Python
module.
print(2 ** 100) #print 2 power of 100
x = 'MTS'
print(x * 8) #print MTS 8 times

step2: save the file with .py extension


ex script1.py

step 3: run the file at terminal as follows


$python sample.py
to save the o/p the above program in a text file
$python sample.py > saveit.txt
o/p is stored in saveit.txt file
to display o.p
$cat saveit.txt
o/p
linux2
1267650600228229401496703205376
MTS MTS MTS MTS MTS MTS MTS MTS

modules:
Every python file itself is known as a module. A module can contain
attributes(variables), functions and classes. In order to use the properties of one
module in another module we use the ‘import’ statement. Whenever we import
one module into another module then imported module compiled file will be
generated with .pyc
you can execute the above code at python prompt by importing script1 file
as follows
>>>import sample
>>>from imp import reload
>>>reload(sample)
If you really want to force Python to run the file again in the same session without
stopping and restarting the session, you need to call the reload function available
in the imp standard library module.

A Text editor to create a one-line Python module file called myfile.py in your
working directory, with the following contents:
title = "I like python"
When this file is imported, its code is run to generate the module’s attribute. That
is, the assignment statement creates a variable and module attribute named title.
You can access this module’s title attribute in other components in two different
ways.
First, you can load the module as a whole with an import statement, and then
qualify
the module name with the attribute name to fetch it as follows
>>> import myfile
>>> myfile.title
'I like python'
Alternatively, you can fetch names out of a module with from statements:
>>> from myfile import title
>>> title
'I like python'

module files usually define more than one name to be used in and outside
the files. Here’s an example that defines three:
threenames.py
a = 'satya'
b = 'ganesh'
c = 'gagan'
print(a, b, c)
$python threenames.py
>>> import threenames
satya ganesh gagan
>>>
>>> threenames.b, threenames.c
('ganesh, 'gagan)
>>>
>>> from threenames import a, b, c
>>> b, c
('ganesh', 'gagan')

Using exec to Run Module Files


Strictly speaking, there are more ways to run code stored in module files than
have yet
been presented here. For instance, the exec(open('module.py').read()) built-in
func-
tion call is another way to launch files from the interactive prompt without having
to
import and later reload. Each such exec runs the current version of the code read
from
a file, without requiring later reloads (script1.py is as we left it after a reload in the
prior
section):
% python
>>> exec(open('script1.py').read())

Python data types


Number Types:
int
ex:
>>>x=34454
>>>type(x) #returns type of the variable . type() is predefined method
>>>id(x) # returns add of the varaible . Id() it is a predefined method
o/p<type ‘int’>
12539576
long
>>>x=1234567899876543212345
>>>type(x)
>>>id(x)
o/p<type ‘long’>

Note: python 2.x supports int and long datatypes . Python3.x supports only int
type.
there are 4 types of number systems
1)binary number system
2)octal number system

3)decimal number system


4)hexadecimal number system

1)binary number system


=>base element is 2
=>possible digits are 0 &1
=>every binary number starts with ‘0b’
ex:
>>> i=0b1010
>>> print(i)
o/p 10 =>0*2 pow 0+1* 2 pow 1+0 * pow 2 +1 * 2 pow 3
2)octal number system
=>base element is 8
=>possible digits 0,1,2,....7
=> every octal number starts with ‘0’(zero)
x=0123
o/p 83 =>3*8 pow 0+2*8 pow 1+1* 8 pow 2

3)decimal number system


=>base element is 10
=>possible digits are 0,1,2,3....9
=>default number system in python is decimal number system
ex: x=1234
o/p 1234 =>4*10 pow 0+3*10 pow 1+2* 10 pow 2+1*10 pow 3

4)hexadecimal number system


=>base element is 16
=>every element start with 0x or 0X
=>possible digits are 0,12,..9,a,b,,c,d,e,f
a value is 10
b value is 11
c value is 12
d value is 13
e value is 14
f value is 15
ex: x=0x12ab
o/p 4779
bin() :=
It is used to convert any number system into binary number system
>>> x=0b1010
>>> print bin(x)
0b1010
>>> y=0123
>>> print bin(y)
0b1010011
>>> z=1234
>>> print bin(z)
0b10011010010
>>> p=0x25
>>> print bin(p)
0b100101
oct():=
it is used to convert any number system into ocatl number system
>>> x=0b1010
>>> print oct(x)
012
>>> y=0123
>>> print oct(y)
0123
>>> z=1234
>>> print bin(z)
0b10011010010
>>> p=0x25
>>> print bin(p)
0b100101
hex():=it is used to convert any number system into hexa00 number system

float
>>>x=54565754.4554
>>>type(x)
o/p<type ‘float’>
note: no double data type ,float can store any length of the number
complex
>>> x=3+4j
>>> type(x)
<type 'complex'>
>>> id(x)
140495387402480

bool
>>> x=True
>>> type(x)
<type 'bool'>
>>> id(x)
9431952

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 the three variables are
assigned
to the same memory location. You can also assign multiple objects to multiple
variables.

a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and
b
respectively, and one string object with the value "john" is assigned to the
variable c.

note:
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.
Ex:
>>> x=10
>>> y=20
>>> x
10
>>> y
20
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> s="satya"
>>> s1="satya"
>>> s2="narayana"
>>> s1
'satya'
>>> s2
'narayana'
>>> del s1,s2
>>> s1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's1' is not defined
>>> s2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's2' is not defined

You might also like