Created for
>>> print( type(True) )
<class 'bool'>
>>> print( type(False) )
<class 'bool'>
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 |
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
Operation | Result |
---|---|
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 |
>>> True and False
False
>>> 0 and 1
0
>>> 0 or 1
1
>>> 1 or 0
1
>>> not 1
False
>>> not 0
True
>>> 2 < 1
False
>>> 2 < "1"
...
TypeError: '<' not supported between instances of 'int' and 'str
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.
>>> 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.
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
Statements are executed one after another, as written in code.
if
statement
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))
if False :
print("Statement1")
print("Statement2")
print("Statement3")
if - else
statement
if condition :
block 1
else :
block 2
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!
user_lang = "bg"
if user_lang == "bg":
print("Здравейте")
else:
print("Hello")
print("-" * 20)
Здравейте
--------------------
if - elif - else
statement
if c1 :
block 1
elif c2:
block 2
else:
block 3
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)
random module
, as shown in code shown in next slide.
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
framework