Devdit
 

หาคำใน List Python ด้วยคำสั่ง if in

1.7K

สอนเขียนโปรแกรมหาคำใน List ภาษา Python ด้วยคำสั่ง if ทำงานร่วมกับคำสั่ง in ตัวอย่างจะค้นหาคำว่า banana จากภายในตัวแปรชนิด List สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง หาคำใน List Python ด้วยคำสั่ง if in

l = ['apple', 'orange', 'banana', 'berry']
w = 'banana'
w2 = 'computer'

if( w in l ):
    print( 'found the word', w )

if( w2 not in l ):
    print( 'not found the word', w2 )

ผลลัพธ์

found the word banana
not found the word computer

คำอธิบาย

1. สร้างตัวแปรชนิด List พร้อมข้อมูลเริ่มต้น

2. สร้างตัวแปร w = banana และ w2 = computer จากข้อมูลทั้ง 2 ตัวจะมี w ที่มีอยู่ใน List ส่วน w2 ไม่มีอยู่ใน List

3. ใช้คำสั่ง if in เพื่อเช็คว่าตัวแปร w มีอยู่ในตัวแปร List

4. ใช้คำสั่ง if not in เพื่อเช็คว่าตัวแปร w2 ไม่อยู่ในตัวแปร List

เขียน 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ