Logical Expressions and Conditional Statements

Boolean type

Boolean type

Overview

Most programming languages define a Boolean type, which represents the truth values of logic and Boolean algebra (named after George Boole).
The Boolean data type consists of only 2 values:
True
False
Note, that these are not variables names, but values like 0 and 1!

                >>> print( type(True) )
                <class 'bool'>
                >>> print( type(False) )
                <class 'bool'>
            
Boolean values in Python are used mainly in the Conditional Statements. They are the returned value of the Comparison Operators.

What is True/False in Python?

True/False values for most of the build-in objects:

Type: =False =True
any numeric type 0 (zero) everything else
string "" any non-empty string
sequences and collections empty any non empty

What is True/False in Python - the bool() check

Using the built-in function bool(), we can convert any Python value to True or False


            >>> bool(-42)
            True
            >>> bool(0)
            False
            >>> bool(0.00001)
            True
            >>> bool("ada")
            True
            >>> bool("")
            False

        

Comparison operators

Comparison operators

intro

With Comparison Operations we can check if 2 or more values are equal or if a value is less than other, and so on.
The result of a Comparison Operation is True/False
Comparing objects of different types, except different numeric, will raise a TypeError in Python3! (Can not compare "apples" with "oranges")



            >>> 2 < 1
            False
            >>> 2 < "1"
            ...
            TypeError: '<' not supported between instances of 'int' and 'str
        

the operators

Operation Meaning
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity*
is not negated object identity*

*The identity of an object uniquely identifies where this object is stored in the computer memory.
It will be discussed deeply in the OOP part of the course

examples


            >>> i = 5
            >>> i < 5
            False
            >>> i <= 5
            True
            >>> 9 < 1000
            True
            >>> "9" < "1000"
            False
        

Note, the last example: "9" < "1000", the result is False, because strings are compared lexicographically.

lexicographical comparison

Symbols are compared by their position (codepoint) according to the character code table used.
First the first two items are compared, and if they differ this determines the outcome of the comparison.If they are equal, the next two items are compared, and so on, until either sequence is exhausted.

So, why "9" < "1000" returns False?

If we use the ASCII Codes Table, we see that the ASCII code point for "9" is 57, and for "1" - 49.
So, Python compares 57 < 49 and as the result is False it returns False for the whole expression
You can get the code point for a one-character string using the built-in ord() function

Comparison operator Chaining

Comparison operators in Python can be chained, instead of combining them with logical 'and'

            x = 5

            # equivalent of: 0<x and x<10:
            print(0<x<10)
        

Notes on comparison - Python 2

Note, that Python 2, can compare values from different types


            >>> "2" == 2
            # False

            >>> "2" >= 2
            True

            >>> 2 >= "2"
            False

            >>> 99999 >= "2"
            False
        

Notes on comparison - best practices

When you need a reliable comparison, make sure that you compare values from same type!

If you need, you can convert between built-in types by using some of the Python's Built-in Functions (some of them will be discussed in further themes).


            print("2" == str(2))
            # True

            print(int("2") >= 2)
            # True

            print(99999 >= int("2"))
            # True
        

Logical (Boolean) operators

Logical (Boolean) operators

Overview

Logical operations are used to combine simple comparison operations into more sophisticated.
Like "if the user is adult AND the user is from Bulgaria"


OperationNameResult
x or y Logical OR if x is false, then y, else x
x and y Logical AND if x is false, then x, else y
not x Logical NOT if x is false, then True, else False

where x and y are expressions
and and or returns one of their operands. I.e. not necessary boolean type.
not always returns boolean value
Truth Table, reflecting how Python works
x y AND
x and y
OR
x or y
NOT
not x
T T T (y) T (x) F
T F F (y) T (x) F
F T F (x) T (y) T
F F F (x) F (y) T

Legend: T - true; F - false

Examples


            >>> True and False
            False
            >>> 0 and 1
            0
            >>> 0 or 1
            1
            >>> 1 or 0
            1
            >>> not 1
            False
            >>> not 0
            True
        

More examples


            user_name=''
            user_age = 15
            user_country = 'BG'

            print(user_age>18 and user_country=='BG')
            print(user_age>18 or user_country=='BG')

            # note that the value of logical operations is not always True/False
            print(user_name and 'Anonymous' )
            print(user_name or '***Anonymous***' )
        

            False
            True

            ***Anonymous***
        

Control Flow Statements

Control Flow Statements

Overview

Normal control flow of a Python program defines that statements are executed one after another, as written in code.
The Control Flow statements allows our program to react in one way, if some condition is True, or in another way, if it's False.

if statement

if statement

Syntax


Condition can be any expression, which is evaluated to True/False (recall What is True/False in Python )

                if condition :
                    block 1
            
In Python, to encompass the statements which forms a block, you do not need to put any braces, but each statement have to be indented with the same amount of spaces!

                x = 42

                if x % 2 == 0:
                    print("{} is an even number!".format(x))
            

example - align matters


            if False :
                print("1")
                print("2")
            print("3")
        
print(1) and print(2) forms a block, which will be executed, only if the condition is true.
But print(3) is not in the block, and will be always executed!

if - else statement

Syntax


            if condition :
                block 1
            else :
                block 2
        

example - even/odd number


            x = 41

            if x % 2 == 0:
                print("{} is an EVEN number!".format(x))
            else:
                print("{} is an ODD number!".format(x))

            # OUTPUT
            # 41 is an ODD number!
        

example - hello in BG


            user_lang = "bg"
            if user_lang == "bg":
                print("Здравейте")
            else:
                print("Hello")
            print("-" * 20)
        

            Здравейте
            --------------------
        

if - elif - else statement

Syntax


            if c1 :
                block 1
            elif c2:
                block 2
            else:
                block 3
        


We can have more than one elif statement, as shown in next examples!

example - multinational hello


            user_lang = "it"

            if user_lang == "bg":
                print("Здравейте")
            elif user_lang == "it":
                print("Ciao")
            elif user_lang == "en":
                print("Hello")
            else:
                print("I do not speak your language!")

            print("-" * 20)
        

Conditional expressions (aka Ternary Operator)

Conditional expressions (aka Ternary Operator)

Conditional expressions, often known as "ternary operators" in many programming languages, are a shorthand way of writing conditional statements.
They provide a compact syntax for deciding which of two values to assign to a variable.
In Python, conditional expressions enhance readability and brevity.
The basic syntax of a conditional expression in Python is:

                x if condition else y
            
This expression evaluates condition, and:
If condition is True, the expression evaluates to x.
If condition is False, it evaluates to y.
Example:

                user_age = 5
                print( 'adult' if user_age>=18 else "child" )  # 'adult'

                # above code is equivalent to next if-else statement:
                if user_age>=18:
                    print('adult')
                else:
                    print('child')
            

Statement vs Expression

Statement vs Expression

Expression:
An expression in Python is any combination of literals (like numbers or string values), variables, operators, and calls to functions that return a value.
Expressions need to be evaluated. When Python evaluates an expression, it computes its value.
A simple example of an expression is 2 + 3. When evaluated, Python understands this and computes its value, 5.
Statement:
A statement, on the other hand, is an instruction that Python can execute. Think of it as an action or command.
Statements do something but don't necessarily produce a value.
Examples include assignment statements like x = 5, print statements, if statements, for loops, etc.
Key Differences
Expressions always produce or return a value. Statements do not produce value, they do something.
Expressions can be parts of statements. For example, in x = 5 + 3, the 5 + 3 is an expression, while x = 5 + 3 is a statement.
Statements are more about performing an action, while expressions are about producing a value.

Operator precedence

Operator precedence

Operator precedence determines the order in which operations are processed in an expression.
Incorrect assumptions about this order can lead to bugs and unexpected behaviors.
Reference: Operator precedence table
Examples:

                print( 2 + 3 * 4 )    # Equals 14, not 20
                print( (2 + 3) * 4 )  # Equals 20
            
Best Practices:
Use Parentheses for Clarity: Even when you know the precedence rules, using parentheses can make your expressions clearer and easier to understand for others.
Avoid Complicated Expressions: If an expression is getting too complex, consider breaking it into smaller parts or storing intermediate results in variables.

Homework

Homework

The tasks are given in next gist file
You can copy it and work directly on it. Just put your code under "### Your code here".

These slides are based on

customised version of

Hakimel's reveal.js

framework