Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
ลูป
มีลูปสองประเภทในภาษา Python คือ for และ while
ลูป "for"
ลูป for ทำงานวนซ้ำผ่านลำดับที่ให้มา ตัวอย่างเช่น:
python
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
ลูป for สามารถวนซ้ำผ่านลำดับของตัวเลขโดยใช้ฟังก์ชัน "range" และ "xrange" ความแตกต่างระหว่าง range และ xrange คือฟังก์ชัน range จะคืนค่ารายการใหม่ที่มีตัวเลขของช่วงที่กำหนดไว้ ในขณะที่ xrange จะคืนค่าเป็นตัวสร้างซึ่งมีประสิทธิภาพมากกว่า (Python 3 ใช้ฟังก์ชัน range ที่ทำงานเหมือน xrange) สังเกตว่าฟังก์ชัน range จะเริ่มจากศูนย์
```python # แสดงผล 0,1,2,3,4 for x in range(5): print(x)
```
ลูป "while"
ลูป while ทำงานวนซ้ำตราบใดที่เงื่อนไขบูลีนเป็นจริง ตัวอย่างเช่น:
```python # แสดงผล 0,1,2,3,4
```
คำสั่ง "break" และ "continue"
break ใช้เพื่อออกจากลูป for หรือ while ในขณะที่ continue ใช้เพื่อข้ามบล็อคปัจจุบันและกลับไปยังคำสั่ง "for" หรือ "while" ตัวอย่างบางส่วน:
```python # แสดงผล 0,1,2,3,4
```
เราสามารถใช้ "else" clause กับลูปได้ไหม?
แตกต่างจากภาษาอื่นเช่น C, CPP... เราสามารถใช้ else กับลูปได้ เมื่อเงื่อนไขของคำสั่ง "for" หรือ "while" ไม่เป็นจริงแล้ว โค้ดส่วนใน "else" จะถูกดำเนินการ หากมีการใช้คำสั่ง break ภายในลูป for ส่วน "else" จะถูกข้ามไป สังเกตว่าส่วน "else" จะถูกดำเนินการแม้ว่าจะมีคำสั่ง continue ก็ตาม
นี่คือตัวอย่างบางส่วน:
```python # แสดงผล 0,1,2,3,4 และจากนั้นแสดง "count value reached 5"
```
Exercise
วนซ้ำและแสดงผลเฉพาะตัวเลขคู่จากรายการ numbers ในลำดับเดียวกับที่ได้รับ อย่าแสดงผลตัวเลขใดที่มาหลังจาก 237 ในลำดับ
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
