Flow control involves 3 things: boolean values
, comparison operators
, boolean operators
Boolean value is either True
or False
(capitalize)
Operator | Meaning |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
42.0 == 42
42 == '42'
'string' == 'string'
There are 3 boolean operators: and
, or
, not
(1==2) and (1==1)
1==2 or 1==1
(1==1) and not (1==2)
If statement
if True:
print('Hello')
Else statement
if True:
print('True')
else:
print('False')
Elif statement
condition1 = 5
condition2 = 4
condition3 = 3
if condition1:
print('condition1')
elif condition2:
print('condition2')
elif condition3:
print('condition3')
The indented code is called a block
. A block is made up of lines of code that are indented at the same level. The indentation is how Python tells what parts is inside the if statements block and what isn't. A block begins when the indentation increases and ends when the indentation returns to its previous level.
In the following example, blank string is Falsey
, all others are Truthy
. You can always see for yourself which values are Truthy or Falsey by passing them into the bool()
function e.g. bool('')
returns False
print('Enter a name:')
name = input()
if (name):
print('Thank you for entering a name')
else:
print('You did not enter a name')
Syntax
while True:
# do something
In the IDLE interactive shell, if you get stuck with an infinite loop, press Ctrl+C
for keyboard interrupt.
The break
statement causes the execution to immediately leave the loop without re-checking the condition.
name = ''
while True:
print('Enter your name')
name = input()
if name == 'your name':
break
print('Thank you')
The continue
statement causes the execution to immediately jump back to the start of the loop and re-check the condition.
spam = 0
while spam < 5:
spam = spam + 1
if spam == 3:
continue
print('spam is ' + str(spam))
for loops will loop specific number of times. Keywords break
and continue
can be used in for loops.
seq = [1,2,3,4,5]
for item in seq:
print('hello')
The range()
function is a generator for generating a sequence or list of integers. The function range()
is called with one, two or three arguments.
range(5)
list(range(1, 5))
Range()
with 1 argument
for i in range(5):
print(i)
# range(5) returns range(0, 5)
Range()
with 2 arguments
for i in range(12, 16):
print(i)
Range()
with 3 arguments
for i in range(0, 10, 2):
print(i)
for i in range(5, -1, -1):
print(i)