becoming a pythonist
DESCRIPTION
A small guide for python beginnersTRANSCRIPT
Becoming a PythonistBecoming 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
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.
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
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
What is it used for?
Web Scripting
Database applications
GUI Applications
Steering scientific Applications
XML Processing
Gaming, Images, Serial Ports, Robots and More..
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
Advantages
Readability
It Is Simple to Get Support
Fast to Learn
Reusability
Software quality
Developer Productivity
Program Portability
Support Libraries
Enjoyment
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
>>>
Variable Types
Int a=1 a=1
a=2 a=2
Int b = a b=a
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
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"
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
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'
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]
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']
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
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
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']
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
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
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
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']
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()
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:
---
Web Frameworks for Python
Collection of packages or modules which allow developers to write Web applications
Zope2
Web2py
Pylons
TurboGears
Django
Thank You