มาเขียน Python กันดีกว่า
บทนำ
Python คืออะไร
Python คือภาษา Script แบบ Object ภาษาหนึ่ง ออกแบบและเริ่มพัฒนาโดย Guido van Rossum ณ ปัจจุบัน Python พัฒนาอย่างต่อเนื่องจนถึงรุ่น 2.4.3 (29 มีนาคม 2549)
การติดตั้ง Python
สำหรับคนที่เขียน Python บน Linux สามารถข้ามขั้นนี้ไปได้เลย เพราะ Linux ทุกตัวมี Python อยู่แล้ว แต่สำหรับบางคนที่โชคร้ายที่ใช้
FreeBSD? ก็ต้องลง Python ด้วย เพราะไม่ใช่ของปกติที่มีตั้งแต่ลง รวมไปถึงคนที่ใช้ Windows ด้วยเช่นกัน
Python เป็นภาษาแบบ Open Source ทำให้มี Python หลายแบบ แต่มี 2 ยี่ห้อที่พบเห็นมากที่สุด ได้แก่
ถ้าเป็นบน Linux/UNIX ส่วนใหญ่จะใช้ Python จาก Python.org เพราะมีมาพร้อมกับระบบปฏิบัติการนั้นๆ อยู่แล้ว แต่สำหรับWindows
ActivePython? จะเหมาะกว่าเนื่องจาก
ActivePython? จะเพิ่มโมดูลที่จำเป็นสำหรับการเขียนโปรแกรมติดต่อกับวินโดส์ที่ลึกลับซับซ้อนมาให้ในตัว
Interactive Mode
สวัสดีชาวโลก
Printing
|
You write:
|
You get:
|
print "Hello, World!"
|
Hello, World!
|
print "Jack and Jill went up a hill"
print "to fetch a pail of water;"
print "Jack fell down, and broke his crown,"
print "and Jill came tumbling after."
|
Jack and Jill went up a hill
to fetch a pail of water;
Jack fell down, and broke his crown,
and Jill came tumbling after.
|
print "Jon 'Maddog' Orwant"
|
Jon 'Maddog' Orwant
|
print 'Jon "Maddog" Orwant'
|
Jon "Maddog" Orwant
|
print "Jon \"Maddog\" Orwant"
|
Jon "Maddog" Orwant
|
print """
This is a multiline string literal
enclosed in triple double quotes.
"""
|
This is a multiline string literal
enclosed in triple double quotes.
|
Expressions
Program:
print "(33 + 2) / 5 + 11.5 = ",(33 + 2) / 5 + 11.5
Output:
(33 + 2) / 5 + 11.5 = 18.5
Python has six basic operations for numbers:
| Operation | Symbol | Example |
| Exponentiation | ** | 5 ** 2 == 25 |
| Multiplication | * | 2 * 3 == 6 |
| Division | / | 14 / 3 == 4 |
| Remainder | % | 14 % 3 == 2 |
| Addition | + | 1 + 2 == 3 |
| Subtraction | - | 4 - 3 == 1 |
|
You write:
|
You get:
|
print "14 / 3 = ",14 / 3
print "14 % 3 = ",14 % 3
print
print "14.0 / 3.0 =",14.0 / 3.0
print "14.0 % 3.0 =",14 % 3.0
print
print "14.0 / 3 =",14.0 / 3
print "14.0 % 3 =",14.0 % 3
print
print "14 / 3.0 =",14 / 3.0
print "14 % 3.0 =",14 % 3.0
print
|
14 / 3 = 4
14 % 3 = 2
14.0 / 3.0 = 4.66666666667
14.0 % 3.0 = 2.0
14.0 / 3 = 4.66666666667
14.0 % 3 = 2.0
14 / 3.0 = 4.66666666667
14 % 3.0 = 2.0
|
The order of operations is the same as in math:
- parentheses ()
- exponents **
- multiplication *, division \, and remainder %
- addition + and subtraction -