Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

อะไรทำให้ Python Cool?


ในบทความนี้ เราจะเรียนรู้เกี่ยวกับฟีเจอร์อะไรบ้างที่ทำให้ Python cool และแตกต่างจากภาษาอื่นๆ

>>> import this

ผลลัพธ์

The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
The 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!

การสลับค่าตัวแปรสองตัวในบรรทัดเดียว

เราสามารถกำหนดค่าให้ตัวแปรหลายตัวพร้อมกันในรูปแบบคำสั่งเดียวได้ ดังที่แสดงด้านล่าง

ตัวอย่าง

a = 201
b = 786
print("Before swapping value of a =" + str(a) + " and b = " + str(b))
# Before swapping value
a, b = b, a
print("After swapping value of a =" + str(a) + " and b = " + str(b))
# After swapping value

ผลลัพธ์

Before swapping value of a =201 and b = 786
After swapping value of a =786 and b = 201

Enumerate type

Enumerated type ใช้สำหรับท่องลิสต์และประเภทคล้ายกันโดยไม่ต้องรู้ความยาวของพวกมันจริงๆ

ตัวอย่าง

mylist = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
for i, value in enumerate(mylist):
    print(i, ':', value)

ผลลัพธ์

0 : t
1 : u
2 : t
3 : o
4 : r
5 : i
6 : a
7 : l

Zip method

ด้วยการใช้ zip method เราสามารถท่องหลายลิสต์พร้อมกันได้ ตามโค้ดด้านล่าง

ตัวอย่าง

mylist1 = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
mylist2 = ['p', 'o', 'i', 'n', 't']
for i, j in zip(mylist1, mylist2):
    print(i, ':', j)

ผลลัพธ์

t : p
u : o
t : i
o : n
r : t

การกลับลำดับลิสต์ (Reversing the list)

ด้วยการใช้ built-in reversed() method เราสามารถได้ลิสต์ที่กลับลำดับโดยตรงโดยไม่ต้องใช้โครงสร้างลูป

ตัวอย่าง

list_inp = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
print(list(reversed(list_inp)))

ผลลัพธ์

['l', 'a', 'i', 'r', 'o', 't', 'u', 't']

ใช้ Interactive "_" Operator

ตัวดำเนินการนี้ใช้บนคอมมานด์ไลน์เพื่อพิมพ์หรือแสดงผลลัพธ์ของการดำเนินการก่อนหน้าที่ทำไป

>>> 12 + 12
24
>>> _
24
>>> print(_)
24

เช่นที่เราทุกคนรู้ว่า ไม่จำเป็นต้องประกาศชนิดข้อมูลใน Python และเราสามารถเปลี่ยนชนิดข้อมูลของตัวแปรได้หลายครั้งในโปรแกรม

สรุป

ในบทความนี้ เราได้เรียนรู้ว่ามีฟีเจอร์อะไรบ้างใน Python ที่ทำให้มัน cool และดึงดูดนักเขียนโปรแกรม