if
An if condition can exist on its own, or inside a function, but they are more useful accomanpanied by other optional parts. There may be zero or more ‘elif’ after a if statement (read as else if) and also an else part.
a = 4
if a % 2 == 0:
print('Even Number')
a = 4
if a % 2 == 0:
print('Even Number')
elif a % 4 == 0:
print('Also Even Number')
else:
print('Odd Number')
Logically, if conditional are very useful as filters
#if conditionals can be used in this way as an example
datum = 'hello world'
if type(datum) == int:
print(datum + ' is a integer')
elif type(datum) == str:
print(datum + ' is a string')
elif type(datum) == float:
print(datum + ' is a float')
else:
print(datum + ' is something else')
for
Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. You can read the statement like English, “for x number of times, repeat certain commands”
In the first instance we use the range inbuilt function.
for i in range(10):
print(i*2)
# i will be increased from 0 to 9, hence you can use it like a changing variable
# as the value is updated at the start of the each run in the loop (10 is excluded)
Another way of going through items of a list would be simply to:
words = ['fire', 'sleep', 'dinner', 'supercalifragilisticexpialidocious']
for w in words:
print(w)
# w will be assigned to elements in the list of words by the order, and printed out
while
For loops allow us to loop a certain number of time until a condition is met, but what if we are not sure about the number times I want to do something? We use a while loop. You can read a while loop in English like, “while this is true, I will keep repeating certain commands”
The while loop executes as long as the condition prescribed remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false.
Here we are using fibonacci as an example
spam = 0
limit = 5
while spam < limit:
print('Hello, world.')
spam = spam + 1
You can have a look at this flow chart to understand how this while loop work
continue
Continue gets the code to skip past the rest of the code block to the next iteration. It may be clearer to look at the example below or here
a = 0
while a < 10:
if a % 2 == 1:
a += 1
continue
print(a)
a += 1
break
break ‘breaks’ you out of a loop or code segment. Again, shown below or here
a = 0
while a < 10: if a >= 4:
a += 1
break
print(a)
a += 1