Anda di halaman 1dari 39

What is Python?

An object- oriented, interpreted, high level programming language Is an object oriented scripting language

Easy to learn, read, use


Open Source

Embeddable in applications

History
Invented in 1990 by Guido Van Rossum The name Python stems from "Monty Python's Flying Circus" Python was influenced by ABC and Modula-3 First public release was in 1991

Who is using it?


Google (various projects) NASA (several projects) The popular Bit Torrent peer-to-peer file sharing system is a Python program. Yahoo! (Yahoo mail & groups) The YouTube video sharing service is largely written in Python. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing. Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API.

Data types
Numbers Strings Lists Tuples Dictionaries Objects Modules: flt_num= 10.0 int_num= 25 my_str = Why are u using Perl? my_list = [123, 'spam', 1.23] my_tup = (1, 4 , 32, *fo , abc+) my_dict = ,a : 24, mo : fomy_inst = MyClass(foo)
import myfile

Numbers
Integers: >>> my_int = 4 >>>my_int / 3 1 Floating Point: >>> my_float = 5.5 >>> 20/my_float 3.6363636363636362

Strings
Strings are immutable There is no char type like in C++ or Java + is overloaded to do concatenation

>>> x = 'hello' >>> x = x + ' there' >>> x 'hello there'

Strings
"hello"+"world "hello"*3 "hello"[0] "helloworld" "hellohellohello" "h" # concatenation # repetition # indexing

"hello"[-1]
"hello"[1:4] len("hello") "e" in "hello

"o"
ell" 5 1

# (from end)
# slicing # size # search

String Formatting
Similar to Cs printf <formatted string> % <elements to insert> Can usually just use %s for everything, it will convert the object to its String representation.
>>> "One, %d, three" % 2 'One, 2, three >>> "%d, two, %s" % (1,3) '1, two, 3 >>> "%s two %s" % (1, 'three') '1 two three

Lists
Ordered collection of data Data can be of different types Lists are mutable Same subset operations as Strings
>>> x = [1,'hello', (3 + 2j)] >>> x [1, 'hello', (3+2j)] >>> x[2] (3+2j) >>> x[0:2] [1, 'hello']

List Methods
append(x) add x to the end of the list insert( i, x) insert x at a position i remove(x) remove first item equal to x pop() remove item at the end of list sort() sort the list reverse() reverse the list

Examples
>>> a = range(5) >>> a.append(5) >>> a.pop() >>> a.insert(0, 42) >>> a.pop(0) >>> a.reverse() >>> a.sort() # [0,1,2,3,4] # [0,1,2,3,4,5] # [0,1,2,3,4] # [42,0,1,2,3,4] # [0,1,2,3,4] # [4,3,2,1,0] # [0,1,2,3,4]

Tuples
Tuples are immutable versions of lists Coded in parentheses >>> T = ('spam', 3.0, [11, 22, 33]) >>> T[1] 3.0 >>> T[2][1] 22
>>> x = (1,2,3) >>> x[1:] (2, 3)
>>> x[0] 1 >>>len(x) 3

Dictionaries
A set of key-value pairs Dictionaries are mutable

>>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]} >>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]}

>>> d['blah'] [1, 2, 3]

Dictionaries: Add/Modify
Entries can be changed by assigning to that entry Assigning to a key that does not exist adds an entry
>>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]} >>> d['two'] = 99 >>> d {1: 'hello', 'two': 99, 'blah': [1, 2, 3]} >>> d[7] = 'new entry' >>> d {1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}

Dictionaries: Deleting Elements


The del method deletes an element from a dictionary
>>> d {1: 'hello', 2: 'there', 10: 'world'}
>>> del(d[2]) >>> d {1: 'hello', 10: 'world'}

Variables
Are not declared, just assigned The variable is created the first time you assign it a value Are references to objects Everything in Python is an object Variables must be assigned before they can be used in expressions

Control Flow Statements


If Statements For Loops While Loops

If Statements
>>> x = 'killer rabbit' >>> if x == 'roger': print("how's jessica?") elif x == 'bugs': print("what's up doc?") else: print('Run away! Run away!') Run away! Run away!

No Braces???
Python uses indentation instead of braces to determine the scope of expressions All lines must be indented the same amount to be part of the scope (or indented more if part of an inner scope) This forces the programmer to use proper indentation since the indenting is part of the program!

While Loops
While Loop:
x=1 >>> import whileloop 1 2 3 4 5 6 7 8 9 >>>

while x < 10 : print x x=x+1

In whileloop.py

For Loops
>>>for var in sequence: statements range() function generates lists of numbers : range (5) -> [0,1,2,3,4]
Example:

mylist=*hello,hi,hey,!+; for i in mylist: print i

Grouping Indentation
In Python
for i in range(20):

In C
for (i = 0; i < 20; i++) { if (i%3 == 0) { printf("%d\n", i); if (i%5 == 0) { printf("Bingo!\n"); } } printf("---\n"); }

if i%3 == 0: print i if i%5 == 0:


print "Bingo!" print "---"

0 Bingo! ------3 ------6 ------9 ------12 ------15 Bingo! ------18 -----

Loop Control Statements


break Jumps out of the closest enclosing loop

continue

Jumps to the top of the closest enclosing loop

Functions
Use the 'def' statement Function body follows; indented! Basic Def: def name ([arg 1 , arg 2, +): statement 1 . statement n [return [expression]]

Example Function
def greet(name):
print 'hello', name
greet('Jack') greet('Jill') greet('Bob')

The return Statement:


The statement return [expression] exits a function, optionally passing back an expression to the caller. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them. total = arg1 + arg2 print "Inside the function : ", total return total;

# Now you can call sum function total = sum( 10, 20 ); print "Outside the function : ", total

Defining a Class
A class is a special data type which defines how to build a certain kind of object Classes are designed to create and manage new objects Instances are objects that are created which follow the definition given inside of the class You just define the class and then use it

Methods in Classes
Define a method in a class by including function definitions within the scope of the class block There must be a special first argument self in all of method definitions which gets bound to the calling instance There is usually a special method called __init__ in most classes

Example
>>> class ExampleClass:
def __init__(self, some_message): self.message = some_message print "New Class instance created, with message:" print self.message >>> first_instance = ExampleClass("message1") New Class instance created, with message: message1 >>> second_instance = ExampleClass("message2") New Class instance created, with message: message2

Instantiating Objects
There is no new keyword as in Java. Just use the class name with ( ) notation and assign the result to a variable __init__ serves as a constructor for the class. Usually does some initialization work The arguments passed to the class name are given to its __init__() method

Constructor: __init__
An __init__ method can take any number of arguments. __init__ is a kind of constructor, when an instance of a class is created. However, the first argument self in the definition of __init__ is special

Self
The first argument of every method is a reference to the current instance of the class By convention, we name this argument self In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called Similar to the keyword this in Java or C++ But Python uses self more often than Java uses this

Deleting instances: No Need to free


When you are done with an object, you dont have to delete or free it explicitly. Python has automatic garbage collection. Python will automatically detect when all of the references to a piece of memory have gone out of scope. Automatically frees that memory. Theres also no destructor method for classes

Importing and Modules


Use classes & functions defined in another file

A Python module is a file with the same name (plus the .py extension)
Like Java import, C++ include Three formats of the command: import somefile from somefile import * from somefile import className The difference? What gets imported from the file and what name refers to it after importing

import
import somefile Everything in somefile.py gets imported. To refer to something in the file, append the text somefile. to the front of its name: somefile.className.method(abc) somefile.myFunction(34)

from import *
from somefile import * Everything in somefile.py gets imported Take care! Using this import command can easily

overwrite the definition of an existing function or


variable! className.method(abc) myFunction(34)

from import
from somefile import className Only the item className in somefile.py gets imported. Take care! Overwrites the definition of this name if already defined in the current namespace! className.method(abc) imported

myFunction(34)

Not imported

Compared to Java
Code up to 5 times shorter and more readable

Multiple inheritance
Quicker development no compilation phase less typing Yes, it may run a bit slower

but development is much faster


and Python uses less memory (studies show)

Compared to C/C++
Python code is often 5-10 times shorter than equivalent C++ code! No compilation phase No need to declare the variables.

Anda mungkin juga menyukai