Logical Expressions and Conditional Statements

Boolean type

What?

Most programming languages define a Boolean type, which represents the truth values of logic and Boolean algebra (named after George Boole).
Boolean values in Python are used mainly in the Conditional Statements and Logical Operations.

The Boolean type

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'>
		

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 object constructor 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

		

Logical (Boolean) operators

OperationResult
x or y if x is false, then y, else x
x and y if x is false, then x, else y
not x if x is false, then True, else False

Examples


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

		

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
		

Notes on comparison - Python 2

docs.python.org/2/ - Value comparisons:
"The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects do not need to have the same type."
"The value of an object is a rather abstract notion in Python"
"The default behavior for equality comparison (== and !=) is based on the identity of the objects"
"The default order comparison (<, >, <=, and >=) gives a consistent but arbitrary order."

Notes on comparison - Python 2 - examples


			>>> "2" == 2
			# False

			>>> "2" >= 2
			True

			>>> 2 >= "2"
			False

			>>> 99999 >= "2"
			False
		

Notes on comparison - Python 3

docs.python.org/2/ - Value comparisons:
"The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality"
"A default order comparison (<, >, <=, and >=) is not provided; an attempt raises TypeError."

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).

For objects comparison you can implement rich comparison methods (will be discussed in OOP themes)

Notes on comparison - best practices - examples


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

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

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

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*

Objects identity will be discussed 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 Unicode code point for a one-character string using the built-in ord() function

Control Flow Statements

What?

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.

Normal Control Flow

Statements are executed one after another, as written in code.

if statement

Syntax

Condition can be any expression, which could be evaluated to True/False



			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!

example


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

example - align matters


			if False :
				print("Statement1")
			  print("Statement2")
			print("Statement3")
		
Statement1 and Statement2 forms a block, which will be executed, only if the condition is true. This is not the case in example above, that's why only Statement3 will be executed.

if - else statement

Syntax


			if condition :
				block 1
			else :
				block 2
		

Flow

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))
		

			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!

Flow

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)
		

Exercises

odd_or_even.py

Write a program, which will print out for any integer number if it is odd or even.
Be careful with the zero!

The BMI by categories

Refine the BMI program form the (last lab)
Now, the output of your program should be the BMI category, corresponding to the BMI index

Guess the number game - the beginning

Write a simple Python program, implementing the "Guess the number" game, following the rules:
The program will "think" of a number using the random module, as shown in code shown in next slide.
You have to implement now only the first user move:
Prompt the user for his/her guess
If the user guess is equal to the machine number => print out a congratulation message!
If the user guess is less than the machine number => print out "your guess is less than my number. Try again!"
If the user guess is greater than the machine number => print out "your guess is greater than my number. Try again!"

Guess the number game - the beggining


			from random import randint
			machine_number = randint(1,10)

			print("machine_number={}".format(machine_number))

			### your code goes bellow:

		

These slides are based on

customised version of

Hakimel's reveal.js

framework