The Power and Simplicity of Python Programming

 
Python
 
Ko-Lung Yuan
 
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
 
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 only 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!
 
Python
之禪
 
美麗優於醜陋,明講好過暗諭。
簡潔者為上,複雜者次之,繁澀者為下。
平舖善於層疊,勻散勝過稠密;以致輕鬆易讀。
特例難免但不可打破原則,務求純淨卻不可不切實際。
斷勿使錯誤靜靜流逝,除非有意如此。
在模擬兩可之間,拒絕猜測的誘惑。
總會有一種明確的寫法,最好也只有一種,
但或須細想方可得。
凡事雖應三思後行,但坐而言不如起而行。
難以解釋的實作方式,必定是壞方法。
容易解釋的實作方式,可能是好主意。
命名空間讚,吾人多實用。
 
蟒之道
 
妍優於寢 喻莫如敘 是故簡勝繁 繁勝亂
平舖勝汲營 綿密不如疏俊 唯平易而已
無例外於其例 不獨清於實際
毋默於誤 其惡非務
寧戚戚於尋徑 勿揣揣於模稜
道謀於一 可以得矣
力行者宜立行於當下 利行者長三思而後行
不可說之說不可說 可以道之道可以道
名域鳴於域 可取
 
How to Get Python
 
Official website: 
http://www.python.org/
 
Install Python
 
Python Interpreter and Libraries
 
 
 
 
 
 
Linux
: sudo apt-get install python3.1-dev
 
IDLE
 
A basic but useful editor for Python
 
 
 
Text-Indent
Keyword-Highlight
Interactive interface
Easy to test code
 
First, We should know…
 
No semicolon ( 
;
 )
No brace ( 
{ }
 )
Using colon ( 
:
 )
 
Using text-Indent
 
X
 
X
 
O
 
O
 
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 = 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 ( 
raw_input( 
[hint]
 
) 
)
raw_input(“name:”)
 
String
 
Using quote ( 
‘ ’
, 
“ ”
, 
“”” ”””
 )
s1=‘apple’
s2=“banana”
s3=“””I love you”””
print(s1,s2,s3)
Strings are unchanged object
Using 
escape characters(e.g. /n)
 
String Operation
 
Concatenate( 
+
 
)          
“alcom”+”lab”
Repeat( 
*n
 
)               
“go”*3
Length( 
len() 
)        
len(“three”)
Exist( 
in
 )                       
‘a’ in ‘apple’
Split( 
.split(“string”)
  
)   
“abc cde”.split(“ ”)
 
Mathematic Type
 
Integer
 - no limit
123123123112432532643877698709760909
Float
 – Not exact, support science notation
123.456
1.2e-3
Complex number
1+2j
1.23+34.7+5j
 
Mathematic Operation
 
Basic operation 
+  -  *  /  %
Floating Point –
base on simple one
10/3
50*0.5
10+3j-3j
 Special operation 
** //
16**0.5
10.0//3.0
 
 
 
   All things in python are objects!
 
List
 
An ordered data structure (Like array)
Mutable Sequence
[object 1, object 2, …]
listex = [1, 2.34, ”alcom”, 7+8j]
Support Nested List
nestlist = [ [1,2,3] , [4.2, “john”], Var]
Access method
listex[-1]
nestlist[0][2]
 
List Operation
 
Length
  
len(nestlist)
Append
  
listex.append(20)
Extend
  
listex.extend([2,3,4])
Count
  
[1,1,2,3].count(1)
Index
  
[1,1,2,3].index(1)
Insert
  
[1,1,2,3].insert(1,1)
Pop
   
[1,1,2,3].pop()
Remove
  
[1,1,2,3].remove()
Reverse
  
[1,2,3,4].reverse()
Sort
  
[1,2,3,4].sort()
 
Dictionary
 
Dictionary is a mapping object
Key 
 value
D = { key1:value1, key2:value2, …}
D[key] = value
D[key]
Dictionary is unordered
Set
 is another unordered data structure
 
Slice
 
S[ i ]
S[ i : j ]
S[ i : j : k ]
Some examples
 
 
If else
 
if     condition:
elif  condition:
else:
PS : Text-Indent!!
 
Logical Operation
 
==
!=
< > <= >=
Or
And
Not
Boolean value: 
True  False
 
For Loop
 
For  
Var
   in  
container
:
 
…code…
 
…code…
 
For  
Var
   in  
range(x)
:
 
…code…
 
…code…
 
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
  
if a 
in
 “abc”
2.
for iteration
  
for a 
in
 list:
 
List Comprehension
List   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List2 = [item*10  
for 
 item  
in
  List]
 
While Loop
 
While
 condition:
…code…
 
While
 
True
:
…code…
 
 
Nested Structure
 
We can use nested structure in python
For loop
While loop
If elif else
 
Build-in Function
 
Length: 
len()
Sort: 
sorted()
V.s. 
object.sort()
 
Function Factory
 
Change object type!
int( )
str( )
float( )
 
Module / Import / Namespace
 
A .py file is a 
module
 whose name is same as
the file name
Use module by 
import
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.function_name(parameters,
 appointed parameter1=value,
 appointed parameter2=value, …)
 
Other important issues
 
User Object
File IO (simple demo)
Exception Handling
Pypi
pickle
 
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
 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 the return value
import popen2
stdout, stdin = popen2.popen2(“ls”)
ostr = stdout.read()
print(ostr)
 
Python with C/C++
 
http://docs.python.org/extending/extending.
html
 
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 Python3
Python Essential Reference
Learning Python
 
Useful Websites
 
http://ez2learn.com/index.php/python-
tutorials
http://wiki.python.org.tw/
http://caterpillar.onlyfun.net/Gossip/Python/i
ndex.html
http://pypi.python.org/pypi
Slide Note
Embed
Share

Python is praised for its simplicity, elegance, and readability, making it an ideal choice for beginners and experts alike. This versatile language is object-oriented, dynamic, and highly productive with a vast array of libraries and an active community. Python's history, Zen philosophy, and practical usage make it a top choice for various applications. From installation to basic syntax, this guide provides an overview of Python's key features and benefits.

  • Python Programming
  • Simplicity
  • Readability
  • Versatility
  • Productivity

Uploaded on Sep 24, 2024 | 1 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Python Ko-Lung Yuan

  2. 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

  3. Pythons history http://zh.wikipedia.org/wiki/Python Guido van Rossum

  4. 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 only 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!

  5. Python

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

  7. Install Python Python Interpreter and Libraries Linux: sudo apt-get install python3.1-dev

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

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

  10. 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

  11. 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!

  12. Input and Output Output ( print() ) print(100) print( a= ,a) Input ( raw_input( [hint]) ) raw_input( name: )

  13. String Using quote ( , , ) s1= apple s2= banana s3= I love you print(s1,s2,s3) Strings are unchanged object Using escape characters(e.g. /n)

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

  15. Mathematic Type Integer - no limit 123123123112432532643877698709760909 Float Not exact, support science notation 123.456 1.2e-3 Complex number 1+2j 1.23+34.7+5j

  16. Mathematic Operation Basic operation + - * / % Floating Point base on simple one 10/3 50*0.5 10+3j-3j Special operation ** // 16**0.5 10.0//3.0

  17. All things in python are objects!

  18. List An ordered data structure (Like array) Mutable Sequence [object 1, object 2, ] listex = [1, 2.34, alcom , 7+8j] Support Nested List nestlist = [ [1,2,3] , [4.2, john ], Var] Access method listex[-1] nestlist[0][2]

  19. 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()

  20. Dictionary Dictionary is a mapping object Key value D = { key1:value1, key2:value2, } D[key] = value D[key] Dictionary is unordered Set is another unordered data structure

  21. Slice S[ i ] S[ i : j ] S[ i : j : k ] Some examples

  22. If else if condition: elif condition: else: PS : Text-Indent!!

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

  24. For Loop For Var in container: code code For Var in range(x): code code

  25. 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]

  26. 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] List2 = [item*10 for item in List]

  27. While Loop While condition: code While True: code

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

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

  30. Function Factory Change object type! int( ) str( ) float( )

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

  32. User Function def funciton_name(parameters[=default value]): function description Call function namespace.function_name(parameters) namespace.function_name(parameters, appointed parameter1=value, appointed parameter2=value, )

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

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

  35. 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

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

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

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

  39. Useful Books Head First Python Dive into Python Programming in Python3 Python Essential Reference Learning Python

  40. Useful Websites http://ez2learn.com/index.php/python- tutorials http://wiki.python.org.tw/ http://caterpillar.onlyfun.net/Gossip/Python/i ndex.html http://pypi.python.org/pypi

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#