ผลต่างระหว่างรุ่นของ "Python Programming/If Statements"
ไปยังการนำทาง
ไปยังการค้นหา
Cardcaptor (คุย | มีส่วนร่วม) |
|||
| แถว 29: | แถว 29: | ||
. | . | ||
</pre> | </pre> | ||
| + | ยกตัวอย่างเช่น (ตัวอย่างนี้ลอกมาจาก [http://www.python.org/doc/2.5.2/tut/node6.html#SECTION006100000000000000000 Python Tutorial) | ||
| + | <pre title="interpreter> | ||
| + | >>> x = int(raw_input("Please enter an integer: ")) | ||
| + | >>> if x < 0: | ||
| + | ... x = 0 | ||
| + | ... print 'Negative changed to zero' | ||
| + | ... elif x == 0: | ||
| + | ... print 'Zero' | ||
| + | ... elif x == 1: | ||
| + | ... print 'Single' | ||
| + | ... else: | ||
| + | ... print 'More' | ||
| + | ... | ||
| + | </pre> | ||
| + | |||
เราสามารถละ <tt>elif</tt> และ <tt>else</tt> ได้เช่นเดียวกับการละ <tt>else</tt> หรือ <tt>else if</tt> ในภาษา C และ Java | เราสามารถละ <tt>elif</tt> และ <tt>else</tt> ได้เช่นเดียวกับการละ <tt>else</tt> หรือ <tt>else if</tt> ในภาษา C และ Java | ||
| − | |||
{{Python Programming/Navigation|Boolean Expressions|Tuples}} | {{Python Programming/Navigation|Boolean Expressions|Tuples}} | ||
รุ่นแก้ไขเมื่อ 18:24, 16 ตุลาคม 2551
คำสั่ง if ในภาษาไพทอนมีรูปแบบดังต่อไปนี้
if <<นิพจน์ทางตรรกศาสตร์ a>>:
คำสั่งที่จะทำเมื่อนิพจน์ทางตรรกศาสตร์ aเป็นจริง #1
คำสั่งที่จะทำเมื่อนิพจน์ทางตรรกศาสตร์ a เป็นจริง #2
.
.
.
elif <<นิพจน์ทางตรรกศาสตร์ b>>:
คำสั่งที่จะทำเมื่อนิพจน์ทางตรรกศาสตร์ b เป็นจริง #1
คำสั่งที่จะทำเมื่อนิพจน์ทางตรรกศาสตร์ b เป็นจริง #2 .
.
.
.
elif <<นิพจน์ทางตรรกศาสตร์ c>>:
คำสั่งที่จะทำเมื่อนิพจน์ทางตรรกศาสตร์ c เป็นจริง #1
คำสั่งที่จะทำเมื่อนิพจน์ทางตรรกศาสตร์ c เป็นจริง #2 .
.
.
.
{{อาจมี elif เพิ่มมากกว่านี้ก็ได้}}
else:
คำสั่งที่จะทำเมื่อนิพจน์ทางตรรกศาสตร์ทั้งหมดไม่เป็นจริง #1
คำสั่งที่จะทำเมื่อนิพจน์ทางตรรกศาสตร์ทั้งหมดไม่เป็นจริง #2 .
.
.
.
ยกตัวอย่างเช่น (ตัวอย่างนี้ลอกมาจาก [http://www.python.org/doc/2.5.2/tut/node6.html#SECTION006100000000000000000 Python Tutorial)
>>> x = int(raw_input("Please enter an integer: "))
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
เราสามารถละ elif และ else ได้เช่นเดียวกับการละ else หรือ else if ในภาษา C และ Java
| หน้าก่อน: Boolean Expressions | สารบัญ | หน้าต่อไป: Tuples |