Python'daki or operatörü, işlenenlerden en az biri True olarak değerlendirilirse True döndüren mantıksal bir operatördür. Düz İngilizce kelimesi "or" olarak yazılan ikili bir operatördür ve koşullu ifadeler, döngüler ve fonksiyon mantığında bileşik Boolean ifadeleri oluşturmak için kullanılır.
Temel or Operatörü Sözdizimi
or operatörü iki işlenen alır ve en az birinin doğru olup olmadığını değerlendirir.
condition1 or condition2 or operatörü, en az bir işlenen True olduğunda True döndürür. Yalnızca her iki işlenen de False olduğunda False döndürür.
Örnek 1: Temel Boolean İfadesi
bool1 = 2 > 3 # False
bool2 = 2 < 3 # True
result = bool1 or bool2
print(result) True
Örnek 2: İkisi de False
bool1 = 2 > 3 # False
bool2 = 5 > 10 # False
result = bool1 or bool2
print(result) False
Her iki koşul da False olduğunda, or operatörü False döndürür.
or Operatörü için Doğruluk Tablosu
or operatörünün farklı boolean kombinasyonlarla nasıl çalıştığını anlamak çok önemlidir.
| Koşul 1 | Koşul 2 | Sonuç |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
or operatörü, en az bir işlenen True olduğunda True döndürür.
Örnek: Tüm Doğruluk Tablosu Durumları
# Case 1: True or True = True
if True or True:
print("Case 1: True") # This executes
# Case 2: True or False = True
if True or False:
print("Case 2: True") # This executes
# Case 3: False or True = True
if False or True:
print("Case 3: True") # This executes
# Case 4: False or False = False
if False or False:
print("Case 4: True")
else:
print("Case 4: False") # This executes Durum 1: True Durum 2: True Durum 3: True Durum 4: False
Combining Multiple Conditions
The and operator is commonly used to combine multiple comparison operations in conditional statements.
Example 1: Age and License Check
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive")
else:
print("You cannot drive") You can drive
Example 2: Number Range Check
number = 15
if number > 10 and number < 20:
print(f"{number} is between 10 and 20") 15 is between 10 and 20
Example 3: Multiple Conditions
a = 10
b = 10
c = -10
if a > 0 and b > 0:
print("The numbers are greater than 0")
if a > 0 and b > 0 and c > 0:
print("All numbers are greater than 0")
else:
print("At least one number is not greater than 0") The numbers are greater than 0 At least one number is not greater than 0
This example shows how and can chain multiple conditions together.
Kısa Devre Değerlendirmesi
or operatörü kısa devre değerlendirmesi kullanır, bir truthy değer bulur bulmaz durur ve kalan işlenenleri değerlendirmez.
Örnek: Kısa Devre Değerlendirmesini Gösterme
def check_first():
print("First condition evaluated")
return False
def check_second():
print("Second condition evaluated")
return True
# Short-circuit in action
if check_first() and check_second():
print("Both are True")
else:
print("At least one is False") İlk fonksiyon çağrıldı True
"İkinci fonksiyon çağrıldı" asla yazdırılmaz çünkü true_func() True döndürdü, bu yüzden Python false_func() değerlendirmesini atladı. Bu optimizasyon performansı artırır ve gereksiz hesaplamaları önler.
Example 2: Avoiding Division by Zero
x = 0
y = 10
# Safe division check
if x != 0 and y / x > 2:
print("y/x is greater than 2")
else:
print("Cannot divide or condition not met") Cannot divide or condition not met
The short-circuit evaluation prevents the division by zero error because x != 0 is False, so y / x is never evaluated.
Using and with Boolean Variables
Boolean variables can be combined directly with the and operator without comparison operators.
Example 1: Direct Boolean Check
is_logged_in = True
has_permission = True
if is_logged_in and has_permission:
print("Access granted")
else:
print("Access denied") Access granted
Example 2: Multiple Boolean Flags
a = 10
b = 12
c = 0
if a and b and c:
print("All numbers have boolean value as True")
else:
print("At least one number has boolean value as False") At least one number has boolean value as False
In Python, 0 evaluates to False in boolean context, while non-zero numbers evaluate to True.
Birden Fazla OR İşlemini Zincirleme
Bir değişkenin herhangi bir değerle eşleşip eşleşmediğini kontrol etmek için birden fazla or operatörünü birlikte zincirleyebilirsiniz.
Örnek 1: OR Operatörlerini Zincirleme
attendance = 85
homework_score = 90
exam_score = 88
if attendance >= 80 and homework_score >= 85 and exam_score >= 85:
print("You passed the course with good grades")
else:
print("Requirements not met") Erişim verildi
Örnek 2: 'in' Kullanan Daha İyi Alternatif
password = "SecurePass123"
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
min_length = len(password) >= 8
if has_upper and has_lower and has_digit and min_length:
print("Password is strong")
else:
print("Password does not meet requirements") Erişim verildi
Example 3: Date Range Validation
year = 2024
month = 6
day = 15
if year > 2000 and month >= 1 and month <= 12 and day >= 1 and day <= 31:
print("Valid date")
else:
print("Invalid date") Valid date
Python 'and' vs Other Languages '&&'
Unlike languages like C, C++, Java, or JavaScript that use && for logical AND, Python uses the keyword and.
Python Syntax:
x = 5
y = 10
if x < y and y < 15:
print("Both conditions are True") Other Languages (JavaScript/Java/C++):
// This does NOT work in Python
if (x < y && y < 15) {
console.log("Both conditions are True");
} Important: Attempting to use && in Python will result in a SyntaxError. Always use the keyword and in Python.
# This will cause an error
# if x > 0 && y > 0: # SyntaxError
# print("Error!")
# Correct Python syntax
if x > 0 and y > 0:
print("Correct!") Combining and with or Operator
You can mix and and or operators in the same expression, but remember that and has higher precedence than or. Use parentheses to control evaluation order.
Example 1: Without Parentheses
age = 25
has_ticket = True
is_vip = False
# and has higher precedence than or
if age >= 18 and has_ticket or is_vip:
print("You can enter") You can enter
This evaluates as: (age >= 18 and has_ticket) or is_vip
Example 2: With Parentheses for Clarity
score = 75
extra_credit = 10
# Explicit grouping
if (score >= 70 and score < 80) or extra_credit >= 20:
print("Grade: B") Grade: B
Example 3: Complex Condition
temperature = 25
is_sunny = True
is_weekend = True
if (temperature > 20 and is_sunny) or is_weekend:
print("Good day for outdoor activities") Good day for outdoor activities
Yaygın Kullanım Durumları
Kullanım Durumu 1: Giriş Doğrulama
username = "alice"
password = "password123"
email = "[email protected]"
if len(username) > 0 and len(password) >= 8 and "@" in email:
print("Registration successful")
else:
print("Please check your input") Geçerli yaş
Kullanım Durumu 2: Varsayılan Değerler
age = 22
citizen = True
registered = True
if age >= 18 and citizen and registered:
print("You are eligible to vote")
else:
print("You are not eligible to vote") Merhaba, Alice! Merhaba, Misafir! Merhaba, Misafir!
Kullanım Durumu 3: İzin Kontrolü
purchase_amount = 150
is_member = True
has_coupon = True
if purchase_amount > 100 and (is_member or has_coupon):
discount = 0.15
final_price = purchase_amount * (1 - discount)
print(f"You qualify for 15% discount. Final price: ${final_price}") Erişim verildi Erişim verildi Erişim reddedildi
Use Case 4: Access Control
user_role = "admin"
is_authenticated = True
session_valid = True
if is_authenticated and session_valid and user_role == "admin":
print("Access granted to admin panel")
else:
print("Access denied") Access granted to admin panel
Use Case 5: Data Validation
data = [1, 2, 3, 4, 5]
if len(data) > 0 and all(isinstance(x, int) for x in data) and min(data) >= 0:
print("Data is valid")
else:
print("Invalid data") Data is valid
Nested Conditions vs and Operator
Using the and operator is often cleaner than nesting multiple if statements.
Nested Approach (Less Readable):
age = 25
income = 50000
if age >= 21:
if income >= 30000:
print("Loan approved")
else:
print("Insufficient income")
else:
print("Age requirement not met") Using and Operator (More Readable):
age = 25
income = 50000
if age >= 21 and income >= 30000:
print("Loan approved")
else:
print("Requirements not met") Loan approved
The second approach using and is more concise and easier to understand.
Kaçınılması Gereken Yaygın Hatalar
Hata 1: OR'u AND ile Karıştırma
# Wrong - SyntaxError
# if x > 0 && y > 0:
# print("Both positive")
# Correct
if x > 0 and y > 0:
print("Both positive") Hata 2: Boolean Dönüş Bekleme
# Ambiguous - may not work as intended
if x > 5 and y > 3 or z < 10:
print("Condition met")
# Better - use parentheses
if (x > 5 and y > 3) or z < 10:
print("Condition met") Mistake 3: Checking Multiple Values Incorrectly
x = 5
# Wrong - doesn't work as expected
# if x == 3 or 5 or 7: # Always True!
# Correct
if x == 3 or x == 5 or x == 7:
print("x is 3, 5, or 7")
# Even better - use 'in'
if x in [3, 5, 7]:
print("x is 3, 5, or 7") Mistake 4: Not Considering Short-Circuit
# Potentially unsafe
# if len(my_list) > 0 and my_list[0] > 10: # Error if my_list doesn't exist
# Safe approach
my_list = []
if my_list and len(my_list) > 0 and my_list[0] > 10:
print("First element is greater than 10") En İyi Uygulamalar
Uygulama 1: Üyelik Kontrolünde 'in' Operatörünü Kullanın
# Clearer with parentheses
if (age >= 18 and age <= 65) and (has_license or has_permit):
print("Can drive") Uygulama 2: Kısa Devre Değerlendirmesinden Yararlanın
# Instead of this:
# if user.age >= 18 and user.has_account and user.verified and not user.banned:
# grant_access()
# Do this:
is_adult = user.age >= 18
has_valid_account = user.has_account and user.verified
not_banned = not user.banned
if is_adult and has_valid_account and not_banned:
print("Access granted") Uygulama 3: Karmaşık Koşullar için Parantez Kullanın
# Put the most likely to fail condition first
def cheap_check():
return True
def expensive_operation():
return True
if cheap_check() and expensive_operation():
print("Both passed") Uygulama 4: Mantıksal ve Bitsel Operatörleri Karıştırmaktan Kaçının
# Poor
# if a and b and c:
# do_something()
# Better
is_authenticated = True
has_permission = True
is_active = True
if is_authenticated and has_permission and is_active:
print("Action allowed") Kendiniz Deneyin
Aşağıdaki kodu değiştirerek öğrendiklerinizi uygulayın. Farklı çıktılar görmek için değerleri ve koşulları değiştirmeyi deneyin!
// Sonuçları görmek için "Kodu Çalıştır"a tıklayın
İlgili Konular
Sık Sorulan Sorular
Python'da 'or' ve '||' arasındaki fark nedir?
Python mantıksal OR işlemleri için or anahtar kelimesini kullanır. || sembolü C, Java ve JavaScript gibi diğer dillerde kullanılır, ancak Python'da SyntaxError hatasına neden olur.
or operatörü her iki koşulu da değerlendirir mi?
Her zaman değil. Python kısa devre değerlendirmesi kullanır—ilk koşul True ise, ikinci koşul değerlendirilmez çünkü sonucun zaten True olduğu bilinmektedir.
or'u ikiden fazla koşulla kullanabilir miyim?
Evet, birden fazla koşulu zincirleyebilirsiniz: if a or b or c or d:. İfadenin True olarak değerlendirilmesi için en az bir koşulun True olması gerekir.
or'un and'ye göre önceliği nedir?
and operatörü or'dan daha yüksek önceliğe sahiptir. Bu, a or b and c ifadesinin a or (b and c) olarak değerlendirildiği anlamına gelir. Netlik için parantez kullanın.
Varsayılan değerler için or'u nasıl kullanırım?
Varsayılan değerler sağlamak için or kullanabilirsiniz: name = user_input or "Misafir". user_input falsy ise (boş, None, vb.), "Misafir" kullanılacaktır.
or'u boolean olmayan değerlerle kullanabilir miyim?
Evet. Python değerleri boolean bağlamında değerlendirir. or ilk truthy değeri döndürür veya hepsi falsy ise son değeri döndürür. Açık bir boolean gerekiyorsa bool() kullanın.