6.5.2 Relational operators
Relational Operators in Programs
Relational operators compare two values and return a Boolean result (True or False). They are the building blocks of every condition in if statements and loops.
| Meaning | Python | C# | VB.NET |
|---|---|---|---|
| Equal to | == | == | = |
| Not equal to | != | != | <> |
| Less than | < | < | < |
| Less than or equal to | <= | <= | <= |
| Greater than | > | > | > |
| Greater than or equal to | >= | >= | >= |
VB.NET uses = for both assignment and equality testing (context determines meaning). Python and C# use = for assignment only; equality is always ==.
Relational Operators in Context
score = int(input("Enter score: "))
PASS = 60
MERIT = 75
DIST = 90
# == and != in selection
if score == 100:
print("Perfect score!")
elif score != 0 and score >= DIST:
print("Distinction")
elif score >= MERIT:
print("Merit")
elif score >= PASS:
print("Pass")
else:
print("Not yet — keep going")
# < and <= in a while loop (input validation)
attempts = 0
MAX = 3
while attempts < MAX:
pin = input("Enter PIN: ")
if pin == "1234":
print("Unlocked")
break
attempts += 1
if attempts >= MAX:
print("Locked")
int score = int.Parse(Console.ReadLine());
const int PASS = 60, MERIT = 75, DIST = 90;
if (score == 100)
Console.WriteLine("Perfect score!");
else if (score != 0 && score >= DIST)
Console.WriteLine("Distinction");
else if (score >= MERIT)
Console.WriteLine("Merit");
else if (score >= PASS)
Console.WriteLine("Pass");
else
Console.WriteLine("Not yet — keep going");
int attempts = 0;
const int MAX = 3;
while (attempts < MAX) {
string pin = Console.ReadLine();
if (pin == "1234") { Console.WriteLine("Unlocked"); break; }
attempts++;
}
if (attempts >= MAX)
Console.WriteLine("Locked");
Dim score As Integer = Integer.Parse(Console.ReadLine())
Const PASS As Integer = 60
Const MERIT As Integer = 75
Const DIST As Integer = 90
If score = 100 Then
Console.WriteLine("Perfect score!")
ElseIf score <> 0 AndAlso score >= DIST Then
Console.WriteLine("Distinction")
ElseIf score >= MERIT Then
Console.WriteLine("Merit")
ElseIf score >= PASS Then
Console.WriteLine("Pass")
Else
Console.WriteLine("Not yet — keep going")
End If
Dim attempts As Integer = 0
Const MAX As Integer = 3
Do While attempts < MAX
Dim pin As String = Console.ReadLine()
If pin = "1234" Then
Console.WriteLine("Unlocked")
Exit Do
End If
attempts += 1
Loop
If attempts >= MAX Then Console.WriteLine("Locked")
Key Takeaways
- Relational operators return
TrueorFalse— they are used inifconditions andwhileloop conditions. - Python/C#: equality is
==; assignment is=. Never mix them up. - VB.NET:
=serves as both assignment and equality;<>is not-equal. - Boundary conditions: use
>=not>when the limit value itself should be included.