Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Overview of Python History of Python

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

DAY – 1

1. Overview of Python
1.1. History of Python:
Python is an easy to learn, powerful and an Opensoruce programming language. It
is a scripting language with Object oriented features. It was invented by Guido Van
Rossum from Netherland in 1989. The first version of Python was released in February
1991. Python 2.0 was released on 16 October 2000.
The current standard versions of Python are: 2.5, 2.6,2.7 and 3.0. Latest version is 3.3
released in September 29 2012.
The name Python came from the “Monty Python's Flying Circus” which impressed
Guido very well.

1.2. Advantages and Disadvantages of Python:


Advantages:
 Open source – Free and can edit source code
 Dynamically typed – No need to specify the type of variable before/after using it.
 Interpreted language – Opposite to compiled langiage.
 Objected oriented language
 Indentation – Whitespaces, No need of brabces.
 Scripting language
 Easy to learn like normal english.
 Developed using ‘C’ language.
 Interface to Other programming languages. – Can include code from C, Java, .Net
using Cython, Jython and IronPython interfaces respectively.
 Platform independent – Works on multi platforms.
 Less code compared to other languages.
 No strict typing on variables and containers.
 Used by Lot many MNCs and worlds top most organizations like Google, NASA, MST
and Gaming apps etc
 Huge library.
 Multi-Threading and Multi processing.

Disadvantages:
 Slow compared to other programming languages like C,C++ or java
 Threading not fully implemented.
 All strings are not Unicode by default (Fixed in 3.0)
 Indentation – If mix tabs and spaces.
1.3. Installing Python:
It is very simple to install python in any platform. Download Python from
http://www.python.org/ and install it at C:\Python27\ For users with 64-bit systems, the
32-bit version of all software is recommended.

Open the Command Prompt and Type into the Command Prompt window:
set path=%path%;C:\Python27\ And hit enter.
You only need to do this once and never again.

You can copy/paste the Python path directly to path variable in


MyComputer>Properties>Advanced Settings> Environment Variables>System variables>
path.

In non-windows platforms it will be installed normally in “/usr/local/bin/python” path.

1.4. Documentation:
Following are the different resources available for Python documentation:
 http://docs.python.org/2/tutorial/ - Official python tutorial
 http://www.python.org/doc/ - Another official Python website.
 http://www.learnpython.org/ - Where you can learn python by executing
the python online.
 http://www.tutorialspoint.com/python/ - From tutorial point.
 http://pythonmonk.com/

1.5. Structure of Python script and IDLE:

Structure of Python Script:


“””
Documentation string related to module.
“””
Import statement -1
Import statement -2
.
.
Global variables declaration
Classes
Functions
Local variable declaration and processing’s.
if __name__ == "__main__":
main()

In non-windows platform we need to add the python path “#!/usr/bin/python and #


coding=utf-8 in the first line of every python module.
IDLE:
IDLE is the Python IDE built with the tkinter GUI toolkit.

IDLE has the following features:

 coded in 100% pure Python, using the tkinter GUI toolkit


 cross-platform: works on Windows and Unix
 multi-window text editor with multiple undo, Python colorizing and many other features,
e.g. smart indent and call tips
 Python shell window (a.k.a. interactive interpreter)
 debugger (not complete, but you can set breakpoints, view and step)

You can use IDLE as a calculator. We can single python statement from Shell. We can also create
and execute Python scripts using IDLE.

To Create New python module: Ctrl+N or File>New


To Save the file: Ctrl+S
To Run the script: Press ‘F5’ or Run>Run Script
Eg:
Type ‘python’ on command line to activate python interpreter or Home>All
Programs>Python>IDLE(GUI). Then it shows the Python Shell as follows:

2. Variables and Data Types:


Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Variables are the first thing you should learn in any new language. You can think of them as
named containers for any kind of data. The syntax to declare them is: name = value You can
name anything you like (except for a handful of keywords), and their values can be any type of
data.

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 have to be explicitly declared 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:

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. While running this program, this will produce 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, 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 types that are used to define the operations possible on them and the storage method
for each of them.

Python has following standard data types:

 Numbers
o Int
o Long
o Float
o complex
 String
 Bool – True or False
 Other data structures like List, Tuple, Dictionary.

Python Numbers:
Number data types store numeric values. They are immutable data types, which means that
changing the value of a number data type results in a newly allocated object.

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 [can also be represented in octal and hexadecimal])

float (floating point real values)

complex (complex numbers)

Examples:
Here are some examples of numbers:
int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

Python allows you to use a lowercase L with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.

A complex number consists of an ordered pair of real floatingpoint numbers denoted by a + bj,
where a is the real part and b is the imaginary part of the complex number.

Python Strings:
Strings in Python are identified as a contiguous set of characters in between 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 following result:

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

3. Data Structures

Control Structures
a. Strings:

Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings:
Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain
your substring. Following is a simple example:
#!/usr/bin/python

var1 = 'Hello World!'


var2 = "Python Programming"

print "var1[0]: ", var1[0]


print "var2[1:5]: ", var2[1:5]
When the above code is executed, it produces following result:
var1[0]: H
var2[1:5]: ytho
Updating Strings:
You can "update" an existing string by (re)assigning a variable to another string. The new value
can be related to its previous value or to a completely different string altogether. Following is a
simple example:
#!/usr/bin/python

var1 = 'Hello World!'

print "Updated String :- ", var1[:6] + 'Python'


When the above code is executed, it produces following result:
Updated String :- Hello Python
Escape Characters:
Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
An escape character gets interpreted; in a singlequoted as well as doublequotes strings.
Backslash Hexadecimal
Description
notation character

\a 0x07 Bell or alert

\b 0x08 Backspace

\cx Control-x

\C-x Control-x

\e 0x1b Escape

\f 0x0c Formfeed

\M-\C-x Meta-Control-x

\n 0x0a Newline

\nnn Octal notation, where n is in the range 0.7

\r 0x0d Carriage return

\s 0x20 Space

\t 0x09 Tab

\v 0x0b Vertical tab

\x Character x

Hexadecimal notation, where n is in the range


\xnn
0.9, a.f, or A.F

String Special Operators:


Assume string variable a holds 'Hello' and variable b holds 'Python' then:
Operator Description Example

a + b will
Concatenation - Adds values on either side of the
+ give
operator
HelloPython

Repetition - Creates new strings, concatenating a*2 will give


*
multiple copies of the same string -HelloHello

a[1] will
[] Slice - Gives the character from the given index
give e

a[1:4] will
[:] Range Slice - Gives the characters from the given range
give ell

Membership - Returns true if a character exists in the H in a will


in
given string give 1

Membership - Returns true if a character does not exist M not in


not in
in the given string a will give 1

Raw String - Suppress actual meaning of Escape


print
characters. The syntax for raw strings is exactly the
r'\n' prints
same as for normal strings with the exception of the
\n
r/R raw string operator, the letter "r," which precedes the
and print
quotation marks. The "r" can be lowercase (r) or
R'\n' prints
uppercase (R) and must be placed immediately
\n
preceding the first quote mark.

See at next
% Format - Performs String formatting
section

String Formatting Operator:


One of Python's coolest features is the string format operator %. This operator is unique to
strings and makes up for the pack of having functions from C's printf() family. Following is a
simple example:
#!/usr/bin/python

print "My name is %s and weight is %d kg!" % ('Zara', 21)


When the above code is executed, it produces following result:
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with %:
Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E

Other supported symbols and functionality are listed in the following table:
Symbol Functionality

* argument specifies width or precision

- left justification

+ display the sign

<sp> leave a blank space before a positive number

add the octal leading zero ( '0' ) or hexadecimal leading


#
'0x' or '0X', depending on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)

% '%%' leaves you with a single literal '%'

(var) mapping variable (dictionary arguments)

m is the minimum total width and n is the number of


m.n.
digits to display after the decimal point (if appl.)

Triple Quotes:
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including
verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python

para_str = """this is a long string that is made up of


several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str;
When the above code is executed, it produces following result:. Note how every single special
character has been converted to its printed form, right down to the last NEWLINE at the end of
the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with
an explicit carriage return at the end of a line or its escape code (\n):
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
Raw String:
Raw strings don't treat the backslash as a special character at all. Every character you put into a
raw string stays the way you wrote it:
#!/usr/bin/python

print 'C:\\nowhere'
When the above code is executed, it produces following result:
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows:
#!/usr/bin/python
print r'C:\\nowhere'
When the above code is executed, it produces following result:
C:\\nowhere
Unicode String:
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as
16-bit Unicode. This allows for a more varied set of characters, including special characters from
most languages in the world. I'll restrict my treatment of Unicode strings to the following:
#!/usr/bin/python

print u'Hello, world!'


When the above code is executed, it produces following result:
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
Built-in String Methods:
Python includes following built-in methods to manipulate strings:
SN Methods with Description

capitalize()
1
Capitalizes first letter of string

center(width, fillchar)
2
Returns a space-padded string with the original string centered to a total of width columns

count(str, beg= 0,end=len(string))


3 Counts how many times str occurs in string, or in a substring of string if starting index beg
and ending index end are given

decode(encoding='UTF-8',errors='strict')
3 Decodes the string using the codec registered for encoding. encoding defaults to the default
string encoding.

encode(encoding='UTF-8',errors='strict')
4 Returns encoded string version of string; on error, default is to raise a ValueError unless
errors is given with 'ignore' or 'replace'.

endswith(suffix, beg=0, end=len(string))


5 Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with suffix; Returns true if so, and false otherwise

expandtabs(tabsize=8)
6
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided
find(str, beg=0 end=len(string))
7 Determine if str occurs in string, or in a substring of string if starting index beg and ending
index end are given; returns index if found and -1 otherwise

index(str, beg=0, end=len(string))


8
Same as find(), but raises an exception if str not found

isalnum()
9 Returns true if string has at least 1 character and all characters are alphanumeric and false
otherwise

isalpha()
10 Returns true if string has at least 1 character and all characters are alphabetic and false
otherwise

isdigit()
11
Returns true if string contains only digits and false otherwise

islower()
12 Returns true if string has at least 1 cased character and all cased characters are in lowercase
and false otherwise

isnumeric()
13
Returns true if a unicode string contains only numeric characters and false otherwise

isspace()
14
Returns true if string contains only whitespace characters and false otherwise

istitle()
15
Returns true if string is properly "titlecased" and false otherwise

isupper()
16 Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise

join(seq)
17 Merges (concatenates) the string representations of elements in sequence seq into a string,
with separator string

len(string)
18
Returns the length of the string
ljust(width[, fillchar])
19 Returns a space-padded string with the original string left-justified to a total of width
columns

lower()
20
Converts all uppercase letters in string to lowercase

lstrip()
21
Removes all leading whitespace in string

maketrans()
22
Returns a translation table to be used in translate function.

max(str)
23
Returns the max alphabetical character from the string str

min(str)
24
Returns the min alphabetical character from the string str

replace(old, new [, max])


25
Replaces all occurrences of old in string with new, or at most max occurrences if max given

rfind(str, beg=0,end=len(string))
26
Same as find(), but search backwards in string

rindex( str, beg=0, end=len(string))


27
Same as index(), but search backwards in string

rjust(width,[, fillchar])
28 Returns a space-padded string with the original string right-justified to a total of width
columns.

rstrip()
29
Removes all trailing whitespace of string

split(str="", num=string.count(str))
30 Splits string according to delimiter str (space if not provided) and returns list of substrings;
split into at most num substrings if given

splitlines( num=string.count('\n'))
31 Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed
startswith(str, beg=0,end=len(string))
32 Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; Returns true if so, and false otherwise

strip([chars])
33
Performs both lstrip() and rstrip() on string

swapcase()
34
Inverts case for all letters in string

title()
35 Returns "titlecased" version of string, that is, all words begin with uppercase, and the rest
are lowercase

translate(table, deletechars="")
36 Translates string according to translation table str(256 chars), removing those in the del
string

upper()
37
Converts lowercase letters in string to uppercase

zfill (width)
38 Returns original string leftpadded with zeros to a total of width characters; intended for
numbers, zfill() retains any sign given (less one zero)

isdecimal()
39
Returns true if a unicode string contains only decimal characters and false otherwise

You might also like