becoming a pythonist

28
Becoming a Pythonist Becoming a Pythonist

Upload: raji-engg

Post on 09-May-2015

373 views

Category:

Education


0 download

DESCRIPTION

A small guide for python beginners

TRANSCRIPT

Page 1: Becoming a Pythonist

Becoming a PythonistBecoming a Pythonist

Page 2: Becoming a Pythonist

What is Python?

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

Python is a case sensitive programming language

Very clear syntax + large and comprehensive standard library

Can run on many platform: Windows, Linux, Mactonish

Page 3: Becoming a Pythonist

History of Python

Created in 1990 by Guido Von Rossum

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other

scripting languages.

Page 4: Becoming a Pythonist

Why Python?

Python is robust

Python is flexible

Designed to be easy to learn and use

Clean, clear syntax

Very few Keywords

Highly Portable

Python reduces time to market

Python is free

Page 5: Becoming a Pythonist

Productivity

Reduced development time

code is 2-10x times shorter than C, C++, Java

Improved Program Maintenance

Code is extremely readable

Less Training

Language is very easy to learn

Page 6: Becoming a Pythonist

What is it used for?

Web Scripting

Database applications

GUI Applications

Steering scientific Applications

XML Processing

Gaming, Images, Serial Ports, Robots and More..

Page 7: Becoming a Pythonist

Python Vs Java

Code 5-10 times more concise

Dynamic typing

Much Quicker Development

No compilation Phase

Less typing

Yes, it runs slower

But development is faster

Python with Java - Jython

Page 8: Becoming a Pythonist
Page 9: Becoming a Pythonist

Advantages

Readability

It Is Simple to Get Support

Fast to Learn

Reusability

Software quality

Developer Productivity

Program Portability

Support Libraries

Enjoyment

Page 10: Becoming a Pythonist

Interactive “Shell”

Great for learning the language

Great for experimenting with the library

Type statements or expressions at prompt:

$python

>>> print “Hello, World”

Hello, World

>>>

Page 11: Becoming a Pythonist

Variable Types

Int a=1 a=1

a=2 a=2

Int b = a b=a

Page 12: Becoming a Pythonist

Basic Datatypes

Integers (default for numbers)

z = 5 / 2 # Answer is 2, integer division.

Floats

x = 3.456

Strings

Can use “” or ‘’ to specify. “abc” ‘abc’ (Same thing.)

“““a‘b“c”””

Boolean

True and False

Page 13: Becoming a Pythonist

Whitespace and Comment

There are no braces to indicate blocks of code for class and function definitions or flow control

Standard indentation is 4 spaces or one tab

# First comment

if True:

print "True"

else:

print "False"

Page 14: Becoming a Pythonist

Look at a sample of code…

x = 34 - 23 # A comment.

y = “Hello” # Another one.

z = 3.45

if z == 3.45 or y == “Hello”:

x = x + 1

y = y + “ World” # String concat.

print x

print y

>>> 12

>>> Hello World

Page 15: Becoming a Pythonist

String Operations

>>> “hello”.upper()

‘HELLO’

>>> print “%s xyz %d” % (“abc”, 34)

abc xyz 34

>>> names = [“Ben", “Chen", “Yaqin"]

>>> ", ".join(names)

‘Ben, Chen, Yaqin‘

>>> " ".join(names)

'BenChenYaqin'

Page 16: Becoming a Pythonist

Lists

Lists are similar to arrays in C

It can store same data type as well as different data type.

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

>>> list[0]

'abcd'

>>> len(list)

5

>>> [1,2,3]+[4,5,6]

[1,2,3,4,5,6]

>>> range(1,5)

[1,2,3,4]

Page 17: Becoming a Pythonist

Built-in List Functions & Methods:

list = ['dora', 55, 'ram', 355.8]

>>> list.append(obj) : list.append('guru') → ['dora', 55, 'ram', 355.8, 'guru']

>>>list.count(obj) : list.count('ram') →1

>>>list.index(obj) : list.index(55) → 1

>>>list.remove(obj) : list.remove(355.8) → ['dora', 55, 'ram', 'guru']

>>>list.reverse() : list.reverse() → ['guru', 'ram', 55, 'dora']

>>>list.pop() : list.pop() → ['guru', 'ram', 55]

>>>list[0:2] : list[0:2] → ['guru', 'ram']

Page 18: Becoming a Pythonist

Tuples

Tuples are sequences, just like lists.

Tuples cannot be updated

read-only lists

>>>tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

>>> tuple[0]

'abcd'

>>> len(tuple)

5

>>> (1,2,3)+(4,5,6)

(1,2,3,4,5,6)

>>>min(tuple)

2.23

Page 19: Becoming a Pythonist

Dictionary

Dictionaries consist of pairs of keys and their corresponding values.

Duplicate key is not allowed.

Keys must be immutable.

Dictionaries are indexed by keys.

>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

>>>dict['Name']

Zara

>>>del dict['Name']

{'Age': 7, 'Class': 'First'}

>>>len(dict)

2

Page 20: Becoming a Pythonist

Built-in Dictionary Functions

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

>>> dict.copy() : dict1 = dict.copy() → {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

>>>dict.clear() : dict1.clear() →{}

>>>dict.get(key) : dict.get('Age') → 7

>>>dict.has_key(key) : dict.has_key('Age') → True

>>>dict.items() : dict.items() → [('Age', 7), ('Name', 'Zara'), ('Class', 'First')]

>>>dict.keys() : dict.keys() →['Age', 'Name', 'Class']

>>>dict.update(dict2) : dict.update(dict2)

>>>dict.values() : dict.values() → [7, 'Zara', 'First']

Page 21: Becoming a Pythonist

Python Loops

For Loop :

for n in range(1, 4): print "This is the number"

While Loop:

n = 3while n > 0: print n, "is a nice number." n = n – 1

Page 22: Becoming a Pythonist

Defining a Function

def sum(numbers):

"""Finds the sum of the numbers in a list."""

total = 0

for number in numbers:

total = total + number

return total

>>>sum(range(1, 5))

>>>10

Page 23: Becoming a Pythonist

Classes

Classes usually have methods. Methods are functions which always take an instance of the class as the first argument.

>>> Class Foo:

... def __init__(self):

... self.member = 1

... def get_member(self):

... return self.member

...

>>> f = Foo()

>>> f.get_member()

>>> 1

Page 24: Becoming a Pythonist

Python Modules

Collection of stuff in foo.py file

A module is a file consisting of Python code

A module can define functions, classes, and variables.

import math

content = dir(math)

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log','log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

Page 25: Becoming a Pythonist

Packages in Python

Collection of modules in directory

Must have __init__.py and contains subpackages.

Consider a file Pots.py available in Phone directory.

Phone/Isdn.py file having function Isdn()

Phone/G3.py file having function G3()

# Now import your Phone Package(__init__.py).

import Phone

Phone.Pots()

Phone.Isdn()

Phone.G3()

Page 26: Becoming a Pythonist

Python Exceptions Handling An exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception immediately otherwise it would terminate and come out.

try:

----

except Exception :

---

else:

---

try:

---

finally:

---

Page 27: Becoming a Pythonist

Web Frameworks for Python

Collection of packages or modules which allow developers to write Web applications

Zope2

Web2py

Pylons

TurboGears

Django

Page 28: Becoming a Pythonist

Thank You