Conditional Structures
I LOVE DOING THIS :)
Basic control flows
Selection (if statements)
Iteration (for loops)
What are For Loops ?
The for
statement line will end with a colon :
and the rest of the code block must be indented with a spacing of 4 spaces. An iterable is any object that can be looped on such as list, tuple, string
>>> fruits = ["apples", "oranges", "mangoes"]
>>> for fruit in fruits:
... print(fruit)
...
apples
oranges
mangoes
>>> fruits = ["apples", "oranges", "mangoes"]
>>> for fruit in fruits:
... size = 0
... for alphabet in fruit:
... size += 1
... print("name of fruit: %s is has length %s" % (fruit, size))
...
name of fruit: apples is has length 6
name of fruit: oranges is has length 7
name of fruit: mangoes is has length 7
Looping on both indexes and items
If we working with the index, then you can call the enumerate
function which returns a tuple of the index and the item
>>> names = ['adi','shiva','gaurav']
>>> for index, name in enumerate(names):
... print('index is %s' % index)
... print('name is %s % name')
...
index is 0
name is adi
index is 1
name is shiva
index is 2
name is gaurav
While Loops ?
While statement will execute a block of code as long as the condition is true
>>> names = ['james','michael','bobby']
>>> length = len(names) // Calculate the length in the list
>>> i = 0
>>> while i < length:
... print(names[i])
... i += 1
...
james
michael
bobby
What are IF blocks ?
>>> num = 44
>>> if num == 42:
... print("number is 42")
... elif num == 44:
... print("num is 44")
... else:
... print("num is neither 42 nor 44")
...
num is 44
Last updated