Not Equal
What Is the Not Equal Operator?
- The not equal operator
!=in Python is used to check if two values are different.
How to Use It:
The basic way to use the not equal operator is:
pythonresult = value1 != value2value1andvalue2are the values you want to compare.resultwill beTrueif the values are not equal, andFalseif they are equal.
Examples and Exercises:
Not Equal Comparison of Numbers:
pythona = 10 b = 12 c = 12 print(a != b) # Output: True print(b != c) # Output: FalseUsing Not Equal Operator in an IF Statement:
pythona = 11 if a % 2 != 0: print(a, "is not an even number.")- Output:
11 is not an even number.
- Output:
Not Equal Operator with Strings:
- You can also compare text.
pythona = "python" b = "javascript" if a != b: print(a, 'and', b, 'are different.')- Output:
python and javascript are different.
Not Equal Operator in a While Loop:
- You can use the not equal operator to control loops.
pythona = 4 while a != 0: print("hello") a -= 1Output:
hello hello hello hello
Not Equal Operator in Compound Conditions:
- Combine conditions using the not equal operator.
pythona = 4 b = 5 if (a == 1) != (b == 5): print('Hello')- Output:
Hello
Summary:
- The not equal operator
!=in Python is used to check if two values are different. It works with numbers, text, and more. Try out the examples to see how it works!