Python da if şart koşulu ile örnekler. Bu örneklerle if, elif ve else kullanımına yönelik örnekleri bulabilirsiniz. Bu şekilde şartlı ifadeler oluşturabileceksiniz
Sadece if kullarak şartlı ifade oluşturma.
# -*- coding: utf-8 -*- lights = ["red","yellow","green"] currentLight = lights[0] print(currentLight) if currentLight == "red": print("Stop!") if currentLight == "yellow": print("Ready!") if currentLight == "green": print("Go!")
Yukarıdaki kod blogun da tüm if ifadeleri gezilecektir. Ancak tüm ifler gezilmesin aranan bulunduğunda işlem sonlanması için aşağıdaki şekilde elif ve else kullanılır. If gerçekleşmezse elif e bak diğer elif gerçekleşmez de sonrakine şeklinde ve en sonda if veya elif ile uymayan bir koşul ise else çalışsın şeklindedir genel mantığı.
# -*- coding: utf-8 -*- lights = ["red","yellow","green","pink"] currentLight = lights[3] print(currentLight) if currentLight == "red": print("Stop!") elif currentLight == "yellow": print("Ready!") elif currentLight == "green": print("Go!") else: print("Wrong Color!")
Örnek: Sayı Pozitif Mi? Negatif Mi?
# -*- coding: utf-8 -*- sayi = int(input("Sayı giriniz ")) if sayi > 0: print("Pozitif") elif sayi == 0: print("Sıfır") else: print("Negatif")
Örnek: En Büyük Sayıyı Bulma
# -*- coding: utf-8 -*- sayi1 = int(input("1. Sayı ...=")) sayi2 = int(input("2. Sayı ...=")) sayi3 = int(input("3. Sayı ...=")) if (sayi1 >= sayi2) and (sayi1 >= sayi3): enBuyuk = sayi1 elif (sayi2 >= sayi1) and (sayi2 >= sayi3): enBuyuk = sayi2 else: enBuyuk = sayi3 print("En büyük sayi = ",enBuyuk)