if, elif, else

if 條件式時常用來判斷是否要執行某個程式片段 if: 當條件成立時,執行此程式片段 elif: 當if 條件不成立時,才判斷elif 是否成立,條件成立時,則執行此片段
else: 當if 或是 elif 條件都不成立時,執行此片段

var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var

print "Good bye!"

Result:

3 - Got a true expression value
100
Good bye!

Practice:

試著完成以下練習:

names = ['James', 'Lucky', 'Alice']
for name in names:
if :
print(name + ' is a boy.')
elif :
print(name + ' is a girl.')
else:
print(name + ' is a dog.')

Result:

James is a boy.
Lucky is a dog.
Alice is a girl.

results matching ""

    No results matching ""