4. 5 #For example : python exam3_1.py Suchart
4 #In MS-DOS prompt, you should type: python name.py your_name
6 #Version 1.0
7 #Written by Mr Suchart
8 #GNU License : You can modify and publish this software everywhere
9
5. 10 import sys 11
12 if len(sys.argv) == 2 : 13 if sys.argv[1] != '' :
14 print("Computer said : Hello, I'm Python!!!")
15 print("Computer said : How are you today?
",sys.argv[1])
16 feeling = input("You said : I'm ")your argv was missing!!!")
17 print("Computer said : Ohh! you are ",feeling,"!!")
6. 18 print("You said : How about you?")
19 print("Computer said : Very good!") 20
21 else :
22 print("Computer said : I cannot talk with you, because
บรรทัดที่1: เครื่องหมาย # คือการ Comment หมายความว่าตัวแปลภาษาจะข้าม
บรรทัดดังกล่าวไป โดยไม่แปลความหมายใดๆ
10. โครงสร้างการเขียนโปรแกรมไพธอน
(Python programming structure)
โดยปกติของภาษาโปรแกรมมิ่งทั่วๆไป ทุกๆโปรแกรมจะมีฟังชันหลักที่เรียกว่า
Main function เสมอ ยกตัวอย่างในโปรแกรมภาษา C ต่อไปนี้
void doit ( int x ) { x = 5; }
int main() {
int z = 27;
doit(z);
fprintf('z is now %dn', z);
return 0; }
11. โครงสร้างภาษาการเขียนโปรแกรมไพธอน
ขอบเขต ตัวอย่างโปรแกรมไพธอน ความหมาย
1 #!/usr/bin/python คอมเมนต์ หรือการประกาศ
ตัวแปลภาษา
2 import sys, getopt นาเข้าไลบารี่ หรือคลาสของ
ไพธอนมาใช้งาน
3 def
display():
print("Python
programming")
def main(): print("I'm
the Main
function") display() if
__name__ == "__main__":
main()
ประกาศตัวแปร ฟังชัน
และคาสั่งควบคุมต่างๆ
รวมถึงฟังชัน main ด้ว
12. ไวยกรณ์พื้นฐานที่จาเป็น
ไวยกรณ์พื้นฐานที่จาเป็นอย่างยิ่งต้องจดจา
1. Case sensitivity: การตั้งชื่อตัวแปร ตัวใหญ่และตัวเล็กถือว่าเป็นคนละตัวแปร
เช่น Number และ number ไม่ใช่ตัวแปรตัวเดียวกัน
2. Space and tabs don’t mix: ไพธอนมองว่า space และ tabs มีความหมายไม่
เหมือนกัน ดังนั้นเวลาเขียนโปรแกรม อย่าผสมระหว่าง space และ tabs เข้าด้วยกันให้
เลือกเอาอย่างใดอย่างหนึ่งเท่านั้น