Python KoLung Yuan Why Python Simple and elegant

  • Slides: 41
Download presentation
Python Ko-Lung Yuan

Python Ko-Lung Yuan

Why Python? • • • Simple and elegant Good readability Object-oriented / dynamic(script) language

Why Python? • • • Simple and elegant Good readability Object-oriented / dynamic(script) language High productivity Abundant resources(libraries…) Active community Wide range of uses Embeddable and Extendibility Interactive Learning / well document

Python’s history • http: //zh. wikipedia. org/wiki/Python Guido van Rossum

Python’s history • http: //zh. wikipedia. org/wiki/Python Guido van Rossum

Zen of Python • • • • • Beautiful is better than ugly. Explicit

Zen of Python • • • • • Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

How to Get Python • Official website: http: //www. python. org/

How to Get Python • Official website: http: //www. python. org/

Install Python • Python Interpreter and Libraries • Linux: sudo apt-get install python 3.

Install Python • Python Interpreter and Libraries • Linux: sudo apt-get install python 3. 1 -dev

IDLE • A basic but useful editor for Python • • Text-Indent Keyword-Highlight Interactive

IDLE • A basic but useful editor for Python • • Text-Indent Keyword-Highlight Interactive interface Easy to test code

First, We should know… ; ) X • No brace ( { } )

First, We should know… ; ) X • No brace ( { } ) X • No semicolon ( : • Using colon ( ) • Using text-Indent O O

Comment • Single-line comment ( #) # This is an example of single-line comment

Comment • Single-line comment ( #) # This is an example of single-line comment • Multi-line comment ( “”” ) “””This is an example of multi-line comment You can write the comment in several lines”””

Variable • Build variable ( Var = … ) Var = 70 Var =

Variable • Build variable ( Var = … ) Var = 70 Var = 6. 78 Var = “alcom lab” • No declaration but definition and type • Naming Rule • No need to worry about where the variables and their sizes, all of the details are hided!

Input and Output • Output ( print() ) print(100) print(“a=”, a) • Input (

Input and Output • Output ( print() ) print(100) print(“a=”, a) • Input ( raw_input( [hint] ) ) raw_input(“name: ”)

String • Using quote ( ‘ ’, “ ”, “”” ””” ) s 1=‘apple’

String • Using quote ( ‘ ’, “ ”, “”” ””” ) s 1=‘apple’ s 2=“banana” s 3=“””I love you””” print(s 1, s 2, s 3) • Strings are unchanged object • Using escape characters(e. g. /n)

String Operation • Concatenate( +) *n ) Length( len() ) Exist( in ) “alcom”+”lab”

String Operation • Concatenate( +) *n ) Length( len() ) Exist( in ) “alcom”+”lab” • Repeat( “go”*3 • len(“three”) • • Split( ‘a’ in ‘apple’ . split(“string”) ) “abc cde”. split(“ ”)

Mathematic Type • Integer - no limit 123123123112432532643877698709760909 • Float – Not exact, support

Mathematic Type • Integer - no limit 123123123112432532643877698709760909 • Float – Not exact, support science notation 123. 456 1. 2 e-3 • Complex number 1+2 j 1. 23+34. 7+5 j

Mathematic Operation • Basic operation + - * / % • Floating Point –base

Mathematic Operation • Basic operation + - * / % • Floating Point –base on simple one 10/3 50*0. 5 10+3 j-3 j • Special operation ** // 16**0. 5 10. 0//3. 0

All things in python are objects!

All things in python are objects!

List • An ordered data structure (Like array) • Mutable Sequence • [object 1,

List • An ordered data structure (Like array) • Mutable Sequence • [object 1, object 2, …] listex = [1, 2. 34, ”alcom”, 7+8 j] • Support Nested List nestlist = [ [1, 2, 3] , [4. 2, “john”], Var] • Access method listex[-1] nestlist[0][2]

List Operation • • • Length Append Extend Count Index Insert Pop Remove Reverse

List Operation • • • Length Append Extend Count Index Insert Pop Remove Reverse Sort len(nestlist) listex. append(20) listex. extend([2, 3, 4]) [1, 1, 2, 3]. count(1) [1, 1, 2, 3]. index(1) [1, 1, 2, 3]. insert(1, 1) [1, 1, 2, 3]. pop() [1, 1, 2, 3]. remove() [1, 2, 3, 4]. reverse() [1, 2, 3, 4]. sort()

Dictionary • Dictionary is a mapping object Key value D = { key 1:

Dictionary • Dictionary is a mapping object Key value D = { key 1: value 1, key 2: value 2, …} D[key] = value D[key] • Dictionary is unordered • Set is another unordered data structure

Slice • S[ i ] • S[ i : j : k ] •

Slice • S[ i ] • S[ i : j : k ] • Some examples

If else if condition: … else: … PS : Text-Indent!!

If else if condition: … else: … PS : Text-Indent!!

Logical Operation • • == != < > <= >= Or And Not Boolean

Logical Operation • • == != < > <= >= Or And Not Boolean value: True False

For Loop For Var in container: …code… For Var in range(x): …code…

For Loop For Var in container: …code… For Var in range(x): …code…

Container • • • Container are the iterative objects List: elements of list Dictionary:

Container • • • Container are the iterative objects List: elements of list Dictionary: keys of dictionary Tuple: elements of tuple File: lines of file range(x): build a list [0, 1, 2, … , x-1]

In and List Comprehension • In is an useful keyword 1. in relation 2.

In and List Comprehension • In is an useful keyword 1. in relation 2. for iteration if a in “abc” for a in list: • List Comprehension List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] List 2 = [item*10 for item in List]

While Loop While condition: …code… While True: …code…

While Loop While condition: …code… While True: …code…

Nested Structure • • We can use nested structure in python For loop While

Nested Structure • • We can use nested structure in python For loop While loop If elif else

Build-in Function len() • Sort: sorted() • Length: V. s. object. sort()

Build-in Function len() • Sort: sorted() • Length: V. s. object. sort()

Function Factory • Change object type! • int( ) • str( ) • float(

Function Factory • Change object type! • int( ) • str( ) • float( )

Module / Import / Namespace • A. py file is a module whose name

Module / Import / Namespace • A. py file is a module whose name is same as the file name • Use module by import sys • Every module has a namespace of its own – Original-> (main) – Import one-> It’s name

User Function • def funciton_name(parameters[=default value]): …function description… • Call function namespace. function_name(parameters) namespace.

User Function • def funciton_name(parameters[=default value]): …function description… • Call function namespace. function_name(parameters) namespace. function_name(parameters, appointed parameter 1=value, appointed parameter 2=value, …)

Other important issues • • • User Object File IO (simple demo) Exception Handling

Other important issues • • • User Object File IO (simple demo) Exception Handling Pypi pickle

Strong Python • • • APPs Website(server program) Linux Shell Script / Linux Managing

Strong Python • • • APPs Website(server program) Linux Shell Script / Linux Managing Latex Combine with C/C++

Python with Linux (1/2) • • #!/usr/bin/python # -*- coding: UTF-8 -*Import os and

Python with Linux (1/2) • • #!/usr/bin/python # -*- coding: UTF-8 -*Import os and shutil os. unlink('data. new. txt') os. rename('data. txt', 'data. alter. txt') shutil. copy('data. txt', 'data. new. txt') shutil. move('data. alter. txt', 'data. txt') chmod a+x python-script-file

Python with Linux (2/2) • Run outer program os. system(“program”) • Pipeline and get

Python with Linux (2/2) • Run outer program os. system(“program”) • Pipeline and get the return value import popen 2 stdout, stdin = popen 2(“ls”) ostr = stdout. read() print(ostr)

Python with C/C++ • http: //docs. python. org/extending. html

Python with C/C++ • http: //docs. python. org/extending. html

Python with Latex • http: //www. texample. net/weblog/2008/oct/2 4/embedding-python-latex/

Python with Latex • http: //www. texample. net/weblog/2008/oct/2 4/embedding-python-latex/

Useful Books • • • Head First Python Dive into Python Programming in Python

Useful Books • • • Head First Python Dive into Python Programming in Python 3 Python Essential Reference Learning Python

Useful Websites • http: //ez 2 learn. com/index. php/pythontutorials • http: //wiki. python. org.

Useful Websites • http: //ez 2 learn. com/index. php/pythontutorials • http: //wiki. python. org. tw/ • http: //caterpillar. onlyfun. net/Gossip/Python/i ndex. html • http: //pypi. python. org/pypi