Computer Science

Python Comparison Operators

Python comparison operators are used to compare two values and return a Boolean result. Common comparison operators include == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to). These operators are essential for making decisions and controlling the flow of a program based on different conditions.

Written by Perlego with AI-assistance

10 Key excerpts on "Python Comparison Operators"

  • Book cover image for: Python Internals for Developers
    eBook - ePub

    Python Internals for Developers

    Practice Python 3.x Fundamentals, Including Data Structures, Asymptotic Analysis, and Data Types

    operators 2 ==3 //Output False “john”==”John” //Output False “john”!=”John” //Output True 2 !=3 //Output True 2 <3 //Output True ‘a’<’b’ //Output True ‘a’>’b’ //Output False 5 >2 //Output True 2 <=2 //Output True 5 >=2 //Output True The preceding example shows different outputs obtained while using comparison operators. Comparison operators can also be used to compare strings like in the preceding example comparison of “john” with “John”. Logical operators Logical operators are used in making decisions for conditions in a program. Logical operators perform operations on True/False operands. The output of the logical operator is either true or false. Table 1.5 describes the various Python logical operators: Operator Unary/Binary Description And Binary Outputs True if both operands are True. Or Binary Outputs True if any of the operands is True. not Unary Outputs True if the operand is false and False if the operand is True. Table 1.5: Python logical operators Note: Unary operators operate on a single operand. The “not” operator requires only one operand as shown in Example 1.7. Example 1.7: Logical operators True and True //Output True True and False //Output False True or False //Output True False or False //Output False not (True) //Output False not (False) //Output True Identity operators Identity operators are like comparison operators. They are used to compare the objects and gives output true if both objects are exactly the same and are stored in the same memory. Identity operators are binary operators. Table 1.6 describes various Python identity operators: Operator Description Is Outputs True if both operands point to the same object. is not Outputs True if both operands point to different objects. Table 1.6: Python identity operators Example 1.8: Identity operators name = “John” test = name name is test //Output True a = 20 b = 20 a is not b //Output False Membership operators Membership operators check if the left operand is a part of the right operand
  • Book cover image for: A Functional Start to Computing with Python
    Comparison: Numeric, General, and Type Comparison operators differ from the standard arithmetic operators because the type of the result is typically different from the arguments: 10>2 ➜ True . The result of comparison is a boolean value, either True or False . The comparison operators are familiar for numeric arguments: 90<100 ➜ True 100<90 ➜ False 100>90 ➜ True 100>100 ➜ False 100>=100 ➜ True (means ≥ in math) 100>=50 ➜ True 100>=200 ➜ False 100<=200 ➜ True (means ≤ in math) 100<>200 ➜ True (means negationslash = in math) 100<>100 ➜ False 100!=200 ➜ True (means negationslash = in math) 100!=100 ➜ False 100==100 ➜ True (means = in math) 100==200 ➜ False Python also allows a “range test” to determine whether a number lies between two values. Examples of this are -200 < 60 < 200.952 ➜ True 1e-4 <= 0.000001 < 8 ➜ False General Comparison Python allows comparison between other types, boolean and sequence, so long as both arguments to the comparison operator have the same type. Thus, strings can be compared to strings, booleans to booleans, and so on. For booleans, the way this works is simple: if we treat False as 0 and True as 1, then all of < > >= <= <> != == behave in the expected manner (but, it turns out we never need to compare booleans to each other). String comparison has a more complicated behavior. There are two ways to understand this, an intuitive way and a formal way. The intuition is alphabetic ordering. Think of where a word, say orbit , would occur in a dictionary. Would it come before or after the word ordinary ? Well, both words are in the “ o ” section of the dictionary, and even the second letter is the same in both words. So we have to look at the third letter to decide: b comes before d in the alphabet, so orbit should come before ordinary in the dictionary. Put Operators 45 another way, orbit has “lower alphabetic ranking” than ordinary —so orbit < ordinary in some sense.
  • Book cover image for: Introduction to Computing Using Python
    eBook - PDF

    Introduction to Computing Using Python

    An Application Development Focus

    • Ljubomir Perkovic(Author)
    • 2015(Publication Date)
    • Wiley
      (Publisher)
    In an algebra class, expressions other than alge- braic expressions are also common. For example, the expression 2 < 3 does not evaluate to a number; it evaluates to either True or False (True in this case). Python can also evaluate such expressions, which are called Boolean expressions. Boolean expressions are expres- sions that evaluate to one of two Boolean values: True or False. These values are said to be of Boolean type, a type just like int and float and denoted bool in Python. Comparison operators (such as < or >) are commonly used operators in Boolean ex- pressions. For example: >>> 2 < 3 True >>> 3 < 2 False >>> 5 - 1 > 2 + 1 True The last expression illustrates that algebraic expressions on either side of a comparison operators are evaluated before the comparison is made. As we will see later in this chapter, algebraic operators take precedence over comparison operators. For example, in 5 - 1 > 2 + 1, the operators - and + are evaluated first, and then the comparison is made between the resulting values. Section 2.1 Expressions, Variables, and Assignments 19 In order to check equality between values, the comparison operator == is used. Note that the operator has two = symbols, not one. For example: >>> 3 == 3 True >>> 3 + 5 == 4 + 4 True >>> 3 == 5 - 3 False There are a few other logical comparison operators: >>> 3 <= 4 True >>> 3 >= 4 False >>> 3 != 4 True The Boolean expression 3 <= 4 uses the <= operator to test whether the expression on the left (3) is less than or equal to the expression of the right (4). The Boolean expression evaluates to True, of course. The >= operator is used to test whether the operand on the left is greater than or equal to the operand on the right. The expression 3 != 4 uses the != (not equal) operator to test whether the expressions on the left and right evaluate to different values.
  • Book cover image for: An Introduction to Python Programming: A Practical Approach
    eBook - ePub

    An Introduction to Python Programming: A Practical Approach

    step-by-step approach to Python programming with machine learning fundamental and theoretical principles.

    • Dr. Krishna Kumar Mohbey; Dr. Brijesh Bakariya(Author)
    • 2021(Publication Date)
    • BPB Publications
      (Publisher)
    False ). There are various types of relational operators.
    • Greater than (>) : It returns true if the left operand is greater than the right. Example, (a>b ).
    • Greater than or equal to (>=) : It returns true if the left operand is greater than or equal to the right. Example, (a>=b ).
    • Less than (<) : It returns true if the left operand is less than the right. Example, (a<b ).
    • Less than or equal to (<=) : It returns true if the left operand is less than or equal to the right. Example, (a<=b ).
    • Equal to (==) : It returns true if both operands are equal. Example, (a==b ).
    • Not equal to (! =) : It returns true if operands are not equal. Example, (a != b ).
    Example 2.2: x = 10 y = 20 print ("x is equal to y:", x == y) print ("x is not equal to y:", x != y) print ("x is less than y:", x < y) print ("x is greater than y:",  x > y) x = 100 y = 200 print ("x is either less than or equal to y:", x <= y) print ("y is either greater than or equal to y:", y >= x) Output: x is equal to y: False x is not equal to y: True x is less than y: True x is greater than y: False x is either less than or equal to  y: True y is either greater than or equal to y: True

    Assignment and shortcut operators

    It is used in Python to assign values to variables. Suppose x = 10 is a simple assignment operator that assigns the value 10 on the right to the variable x on the left. There are various compound operators in Python, such as x += 10 that adds to the variable and later assigns the same. It is equivalent to x = x + 10 . It is also called a shortcut operator
  • Book cover image for: Fundamentals of Python
    eBook - PDF

    Fundamentals of Python

    Data Structures

    The + operator means concatenation when used with collections, such as strings and lists. The ** operator is used for exponentiation. The comparison operators <, <=, >, >=, ==, and != work with numbers and strings. The == operator compares the internal contents of data structures, such as two lists, for structural equivalence, whereas the is operator compares two values for object identity. Comparisons return True or False. The logical operators and, or, and not treat several values, such as 0, None, the empty string, and the empty list, as False. In contrast, most other Python values count as True. The subscript operator, [], used with collection objects, will be examined shortly. The selector operator, ‘ • ’, is used to refer to a named item in a module, class, or object. The operators have the standard precedence (selector, function call, subscript, arithmetic, comparison, logical, assignment). Parentheses are used in the usual manner, to group sub- expressions for earlier evaluation. The ** and = operators are right associative, whereas the others are left associative. Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 7 Basic Program Elements Function Calls Functions are called in the usual manner, with the function’s name followed by a parenthe- sized list of arguments. For example: min(5, 2) # Returns 2 Python includes a few standard functions, such as abs and round. Many other functions are available by import from modules, as you will see shortly. The print Function The standard output function print displays its arguments on the console.
  • Book cover image for: Data Analysis with Python
    eBook - ePub

    Data Analysis with Python

    Introducing NumPy, Pandas, Matplotlib, and Essential Elements of Python Programming (English Edition)

    Relational operators are used for checking the relation between operand and to compare the values. According to the condition, these operators return ‘True’ or ‘False’ as a result. Please go through the relational operators in Python listed as follows:
    Operator name Operator symbol Description Example
    equal to == compare if the value of the left operand is equal to the value of the right operand a==b
    not equal to != compare if the value of the left operand is not equal to the value of the right operand a!=b
    less than < compare if the value of the left operand is less than the value of the right operand a<b
    greater than > compare if the value of the left operand is greater than the value of the right operand a>b
    less than or equal to <= compare the value of the left operand is less than or equal to the value of the right operand a<=b
    greater than or equal to >= compare the value of the left operand is greater than or equal to the value of the right operand a>=b
    Table 3.2: Relational operators in Python
    The following codes depict the use of relational operators on the variables a and b: Coding example(s) a = 10 b = 8 # equal to relation (==) print(“equal to relation => (a==b) is”, a==b) # not equal to relation (!=) print(“not equal to relation => (a!=b) is”, a!=b) # less than relation (<) print(“less than relation => (a < b) is”, a < b) # greater than relation (>) print(“greater than relation => (a > b) is”, a > b) # less than or equal to relation (<=) print(“less than relation => (a <= b) is”, a <= b) # greater than or equal to relation (>=) print(“greater than relation => (a >= b) is”, a >= b) Output equal to relation => (a==b) is False not equal to relation => (a!=b) is True less than relation => (a < b) is False greater than relation => (a > b) is True less than relation => (a <= b) is False greater than relation => (a >= b) is True

    Assignment operator

    For assigning the value to a variable, we use assignment operators. The following is a list of assignment operators in Python:
  • Book cover image for: Machine Learning For Dummies
    • John Paul Mueller, Luca Massaron(Authors)
    • 2021(Publication Date)
    • For Dummies
      (Publisher)
    When making comparisons, always con-sider operator precedence; otherwise, the assumptions you make about a com-parison outcome will likely be wrong. Working with functions To manage information properly, you need to organize the tools used to perform the required tasks. Each line of code that you create performs a specific task, and you combine these lines of code to achieve a desired result. Sometimes you need TABLE 5-6 Python Operator Precedence Operator Description () You use parentheses to group expressions and to override the default precedence so that you can force an operation of lower precedence (such as addition) to take precedence over an operation of higher precedence (such as multiplication). ** Exponentiation raises the value of the left operand to the power of the right operand. ~ – Unary operators interact with a single variable or expression. * / % // Multiply, divide, modulo, and floor division. – Addition and subtraction. >> << Right and left bitwise shift. & Bitwise AND. ^ | Bitwise exclusive OR and standard OR. <= < > >= Comparison operators. == != Equality operators. = %= /= // = –= = *= **= Assignment operators. is is not Identity operators. in not in Membership operators. not or and Logical operators. CHAPTER 5 Beyond Basic Coding in Python 73 to repeat the instructions with different data, and in some cases your code becomes so long that keeping track of what each part does is hard. Functions serve as orga-nization tools that keep your code neat and tidy. In addition, functions let you easily reuse the instructions you’ve created as needed with different data. This section of the chapter tells you all about functions. More important, in this section you start defining how to create your first serious applications in the same way that professional developers do. Creating reusable functions You go to your closet, take out pants and shirt, remove the labels, and put them on.
  • Book cover image for: Learning Scientific Programming with Python
    For example, >>> a = 4.503 >>> b = 2.377 >>> c = 3.902 >>> s = (a + b + c) / 2 ➊ >>> area = math.sqrt(s * (s - a) * (s - b) * (s - c)) >>> area 4.63511081571606 ➊ Don’t forget to import math if you haven’t already in this Python session. 8 For a complete list of built-in function names, see https://docs.python.org/3/library/functions.html. 9 CamelCase in Python is usually reserved for class names: see Section 4.6.2. 10 https://legacy.python.org/dev/peps/pep-0008/. 18 The Core Python Language I Table 2.5 Python Comparison Operators == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to Example E2.4 The data type and memory address of the object referred to by a variable name can be found with the built-ins type and id: >>> type (a) < class ' float '> >>> id (area) 4298539728 # for example 2.2.4 Comparisons and Logic Operators The main comparison operators that are used in Python to compare objects (such as numbers) are given in Table 2.5. The result of a comparison is a boolean object (of type bool) which has exactly one of two values: True or False. These are built-in constant keywords and cannot be reassigned to other values. For example, >>> 7 == 8 False >>> 4 >= 3.14 True Python is able, as far as possible without ambiguity, to compare objects of different types: the integer 4 is promoted to a float for comparison with the number 3.14. Note the importance of the difference between == and =. The single equals sign is an assignment, which does not return a value: the statement a = 7 assigns the variable name a to the integer object 7 and that is all, whereas the expression a == 7 is a test: it returns True or False depending on the value of a. 11 Care should be taken in comparing floating-point numbers for equality. Since they are not stored exactly, calculations involving them frequently lead to a loss of precision and this can give unexpected results to the unwary.
  • Book cover image for: Basic Core Python Programming
    eBook - ePub

    Basic Core Python Programming

    A Complete Reference Book to Master Python with Practical Applications (English Edition)

    operators . Relational operators are used to compare two values and they return true or false according to the condition.
    Relational operators and their purpose in Python are defined in table 3.3 .
    Operator Purpose
    = = Returns true if two operands are equal.
    != Returns true if two operands are not equal.
    > Returns true if the left operand is greater than the right operand.
    < Returns true if the left operand is smaller than the right operand.
    >= Returns true if the left operand is greater than or equal to the right operand.
    <= Returns true if the left operand is smaller or equal to the right operand.
    Table 3.3: Relational operators and their purpose
    Example 3.3:
    The following box shows the usage of relational operators. Four variables ‘a ’, ‘b ’, ‘c ’ and ‘d ’ are first assigned values, and then relational operators are applied to these variables.
    >>> #Defining Variables
    >>> a = 5 >>> b = 5 >>> c = 4 >>> d = 6 >>> print('a = ',a) a = 5 >>> print('b = ',b) b = 5 >>> print('c = ',c) c = 4 >>> print('d = ',d) d = 6
    >>> #Check for equality using ==
    >>> print('a == b is', a == b) a == b is True >>> print('a == c is', a == c) a == c is False >>>
    >>> #Check for in-equality using !=
    >>> print('a != b is', a == b) a != b is True >>> print('a != c is', a == c) a != c is False >>>
    >>> #Check is greater than using >
    >>> print('a > b is', a > b) a > b is False >>> print('a > c is', a > c) a > c is True >>> print('a > d is', a > d) a > d is False
    >>> #Check is less than using <
    >>> print('a < b is', a < b) a < b is False >>> print('a < c is', a < c) a < c is False
  • Book cover image for: Introduction to Computing Using Python
    eBook - PDF

    Introduction to Computing Using Python

    An Application Development Focus

    • Ljubomir Perkovic(Author)
    • 2012(Publication Date)
    • Wiley
      (Publisher)
    For example, does the expression 2 * 3 + 1 evaluate to 7 or 8? >>> 2 * 3 + 1 7 Table 2.5 Comparison operators. Two numbers of the same or different type can be compared with the comparison operators. Operation Description < Less than <= Less than or equal > Greater than >= Greater than or equal == Equal != Not equal Section 2.4 Objects and Classes 35 Operator Description [expressions...] List definition x[], x[index:index] Indexing operator ** Exponentiation +x, -x Positive, negative signs *, /, //, % Product, division, integer division, remainder +, - Addition, subtraction in, not in, <, <=, >, >=, <>, !=, == Comparisons, including membership and identity tests not x Boolean NOT and Boolean AND or Boolean OR Table 2.6 Operator precedence. The operators are listed in order of precedence from highest on top to lowest at the bottom; operators in the same row have the same precedence. Higher-precedence operations are performed first, and equal precedence operations are performed in left-to-right order. The order in which operators are evaluated is defined either explicitly using parentheses or implicitly using either the operator precedence rules or the left-to-right evaluation rule if the operators have the same precedence. The operator precedence rules in Python follow the usual algebra rules and are illustrated in Table 2.6. Note that relying on the left-to-right rule is prone to human error, and good developers prefer to use parentheses instead.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.