Networking, Security & Cloud Knowledge

Friday, August 24, 2018

Python


Introduction to Python :

Python is a high-level, interpreted, interactive and object-oriented scripting language.

·         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 W W W browsers to games.



History of Python:
Python was developed by Guido van Rossum in the late 80s and early 90s 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.

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



#################### Method to execute Python Code ######################
Interactive mode:
>>> print "Hello, Python!";     ßsyntex for 2.7


Scripted mode:
Open notepad , type following command and save it with .py extension .
print "Hello, Python!";
python test.py


$ chmod +x test.py # This is to make file executable
$./test.py


#########################  Installation ################################

Installation of Python:
For windows
X 64 version for 64 bit OS
X 86 version for 32 bit OS

Document comes with CHM (compiled HTML)


Python  - V to verify version of python  

########################## Vocabulary #############################

Python program flow
·         Program  à module(s)          ----- std library / import  (top level py file)
·         Modules à statements          ----- statement is reserved key word
·         Statements à expression      --- expression is mathematical that operate on data
·         Expressions à objects           ---  anything can be object, data entity



Modules
·         Modules are functions and variables defined in separate files
·         Items are imported using from or import
from module import function
function()

import module
module.function()

·         Modules are namespaces
o   Can be used to organize variable names, i.e.

atom.position = atom.position - molecule.position



Python is: (based on different type of data)
·         Dynamically typed  (e.g   we don’t have to declare type for variable )
·         Strongly typed


################     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.
·         Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.


Here are naming conventions for Python identifiers:
·         Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
·         Starting an identifier with a single leading underscore indicates that the identifier is private
·         Starting an identifier with two leading underscores indicates a strongly private identifier.
·         If the identifier also ends with two trailing underscores, the identifier is a language-defined special name

###############   Lines and Indentation #############################
Blocks of code are denoted by line indentation, no braces used.


The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.

E.g
if True:
  print "True"
else:
  print "False"


### Above statement is correct, but bellow statement give error ######

if True:
 print "Answer"
 print "True"
else:
 print "Answer"
print "False"





###################    Python Keywords  #############################
The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only. 


And
Assert
exec
finally
Not
or
Break
for
pass
Class
from
print
Continue
global
raise
def
if
return
del
import
try
elif
in
while
else
is
with
except
lambda
yield



##########################   DATA TYPES ###########################
Immutable date (Fixed data type)
·         Number
o   Int
o   Float
·         String
·         Tuple           (“Sunday”,”Monday”, 123, “mango”)

Mutable data type (that can be changed or modified)

·         List                [  “Sunday”, “Monday, 123  ]
·         Dictionary    {  1:”Sunday”, 2: “Monday” }      contain key:value pair
·         file



Verify data time using type()  function







  isinstance() --- test for data type (Boolean)








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


PYTHON 2  uses ASCII character only 128 values using 7 bit

PYTHON 3 uses UTF-8  (1 – 4 byte)
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






String operation :

Name = “myname”

Len(name)     --- gives character length
+                    --- concatenation
‘ * ‘                 ---- repetition
str(name)       ----  type casting, changing identity of data type




String slicing:



String method

Object.find()
Name.split()  cuts string @ delimiter



Find location (position) of letter / character in string




Raw string prevent escape sequence interruption





Verify if particular sub-string exist in string 

Syntax:  “text”  not  in  (variable)   returns True  / False


Syntax:  “text” in  returns True / False












Join()




To verify if string consist of alphabet or digit..
Isalpha()

Isdigit()







Byte class provides an immutable sequence. Value must be integers from 0 – 255 to represent a byte.

Byte array class provide an mutable sequence.


######################## Tuples #####################################

Tuples  ()
·         order set of data
·         used for storing static program data
·         Read only data
·         Can be integrated with dictionary
·         Immutable
·         Slicing in tuple


Empty tuple   e.g     tup1 = ()
Single entry tuple   e.g    tup2 = (1,)         , is necessary for single entry.

“a”  in tup1
“a” not in tup1





Range




# set class provide a mapping of unique immutable elements


Exercise.










######################## List #######################################
List  [ ]
·         Can be modified or updated.

List operation :

Append()       à  add 1 element at the end
Count()         à
Extend()        à extend list
Index()
Insert ()        à insert element
Pop()            à remove last element and returns the value, we can use pop using index       to remove specific element.

Remove(0)     à remove element using value, instead of index used in pop
Clear ()          à remove all element

Min()
Max()
Sorted()        à only shows list in sorted
Sort()             à will change original string
Reverse()       à reverse the order

                                        











Dictionary

{key:value}


To retrieve information from dictionary.
  .keys()
   .values()
   .items()
   Pop()                       -- must provide value / key



In dictionary array is associated with hash table and don’t have order, so splicing don’t’ work.



###################### Operator ################################

‘ + ‘  add
‘ – ‘  subtract
‘ * ‘  multiply
‘ / ‘   divide
//     quotient
%    reminder


**  power    e.g 2**4   means   2^4


Comparison    < ,   >  ,   == , !=


Boolean :   AND  , OR , NOT

Order of operation (PEMDAS)
Parenthesis – exponential – Multiplication – Division – Addition – Subtraction 


For more complex maths we can use standard library
1.    fraction
2.    math

external module :  mum py    &    sci py









########################  Date & Time:  ################################
>>> Import datetime

To display today’s date and time:
>>>  datetime.datetime.today()


To display only date
>>> datetime.date.today()





Changing date in DD MM YYYY format


Where   d à Day, b à Month, y à Year




#### File handling  ###

CSV , comma separated value










Open file

F = open (“file_name”, “x”)

X = r  (read only)
   = a  (append)
   = w (write)
   = r+  R/W



File opened using above method should always be closed manually. Using command
f.close()


In case we forgot to close the file, it will remain open.

So to avoid mistake / issue we should open file with context manage


So above command open file with context manage and content is stored in f_contents








f.readline()  -- read line by line from 1st to end

to go back to start use

f.seek(0)


##### copy one file to another file #####





############# Public and Private Data ######################
·         In Python anything with two leading underscores is private
__a, __my_variable
·         Anything with one leading underscore is semiprivate, and you should feel guilty accessing this data directly.
_b
·         Sometimes useful as an intermediate step to making data private


####################### Turtle ###################################

Import turtle
Turtle.Forward(25)                   -move forward by 25
Turtle.backward(30)
Turtle.left(30)                          - rotate left by 30 degree
Turtle.right(30)                        - rotate right  by 30 degree

Turtle.shape(“turtle”)               - changes cursor from triangle to turtle shape
Turtle.exitonclic()                    -  close turtle window on click

Turtle.color(“red”)

To user RGB format for color
Turtle.colormode(255)
Turtle.color(215,100,170)           for pink color

Help(turtle.color)

Turtle.width()                              change width of turtle cursor


 turtle.reset()                       clears the screen
 turtle.undo()

turtle.circle(10)                     where value 10 represent radius


turtle.penup()                       no lines – like pen not touching paper
turtle.pendonw()                  

turtle.title("welcome")              change  name of turtle window



input box inside turtle
>>> title = "input your data"
>>> promt = " what is your name ?"
>>> turtle.textinput(title,promt)
'Santosh'



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.