jika, jika, jika tidak

Python Tingkat Menengah

Hugo Bowne-Anderson

Data Scientist at DataCamp

Gambaran umum:

  • Operator perbandingan
    • <, >, >=, <=, ==, !=
  • Operator Boolean
    • and, or, not
  • Pernyataan Bersyarat
    • if, else, elif
Python Tingkat Menengah

jika

if condition :
    expression

control.py

z = 4

if z % 2 == 0 : # True print("z is even")
z is even
Python Tingkat Menengah

jika

if condition :
    expression
  • expression bukan bagian dari if

control.py

z = 4
if z % 2 == 0 :    # True
    print("z is even")
z is even
Python Tingkat Menengah

jika

if condition :
    expression

control.py

z = 4
if z % 2 == 0 :
    print("checking "  + str(z))
    print("z is even")
checking 4
z is even
Python Tingkat Menengah

jika

if condition :
    expression

control.py

z = 5
if z % 2 == 0 :    # False
    print("checking "  + str(z))
    print("z is even")

Python Tingkat Menengah

jika tidak

if condition :
    expression
else :
    expression

control.py

z = 5
if z % 2 == 0 :    # False
    print("z is even")
else :
    print("z is odd")
z is odd
Python Tingkat Menengah

elif

if condition :
    expression
elif condition :
    expression
else :
    expression

control.py

z = 3
if z % 2 == 0 :
    print("z is divisible by 2")    # False
elif z % 3 == 0 :
    print("z is divisible by 3")    # True
else :
    print("z is neither divisible by 2 nor by 3")
z is divisible by 3
Python Tingkat Menengah

elif

if condition :
    expression
elif condition :
    expression
else :
    expression

control.py

z = 6
if z % 2 == 0 :
    print("z is divisible by 2")    # True
elif z % 3 == 0 :
    print("z is divisible by 3")    # Never reached
else :
    print("z is neither divisible by 2 nor by 3")    
z is divisible by 2
Python Tingkat Menengah

Ayo berlatih!

Python Tingkat Menengah

Preparing Video For Download...