Programming Basics

  Home arrow Programming Basics arrow Logical Operators in Python
PROGRAMMING BASICS

Logical Operators in Python
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating:  stars stars stars stars stars / 0
    2011-07-13

    Table of Contents:
  • Logical Operators in Python
  • Else Statement

  •  
     

    SEARCH CODEWALKERS

    TOOLS YOU CAN USE

    advertisement

    Logical Operators in Python


    (Page 1 of 2 )

    In this second part of a six-part series that explores the Python programming language, we will continue the discussion we started last week on its logical operators. This article is excerpted from chapter two of the book Beginning Game Development with Python and Pygame: From Novice to Professional, written by Will McGugan (Apress; ISBN: 9781590598726).

    Or Operator

    To complement theand operator, we have theoroperator, which results inTrueif either the first or second value isTrue. Let’s say we want to eat fugu if it is tasty or it is very cheap (after all, who can turn down cheap fugu?):

    if fugu == "tasty" or price < 20.0:
    print "Eat the fugu!"

    Just like theandoperator, theor operator has plenty of applications in real life. My car will stop if I run out of gas or the battery goes dead. See Table 2-2 for theor truth table.

    Table 2-2. Truth Table for the Or Operator

    Logic False or False

    Result False

    True or False

    True

    False or True

    True

    True or True

    True

    Not Operator

    The final logic operator we will look at is thenotoperator, which swaps the state of a boolean value, soTruebecomesFalse andFalse becomesTrue(see Table 2-3). You can use this to reverse any condition:

    if not (fugu == "tasty" and price < 100.0):
    print "Don't eat the fugu!"

    Here we have reversed thefugu == "tasty" and price < 100.0condition so that Python runs the code block only if the condition is not true (that is, false).

    Table 2-3. Truth Table for the Not Operator

    Logic

    Result

    not True

    False

    not False

    True

    More Programming Basics Articles
    More By Apress Publishing

    blog comments powered by Disqus

    PROGRAMMING BASICS ARTICLES

    - The Transliteration Operator in Perl
    - Perl String Processing Functions
    - Perl String Processing
    - Control Flow Constructs: Loops Conclusion
    - Loop Control Constructs
    - Control Flow Constructs: the For and Foreach...
    - Loops and Control Flow Constructs
    - Expression Modifiers for Perl Control Flow C...
    - Logical Operators and Control Flow Constructs
    - Comparing Strings with Control Flow Construc...
    - Perl Operators and Control Flow Constructs
    - Control Flow Constructs
    - More Time Manipulation with PHP
    - Validating and Manipulating Dates with PHP
    - Using the Date Constructor in PHP


    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap