Conditionals and Loops
Control flow syntax makes use of colons and indentation or else know as white space.
- if some condition ,then execute some code.
- elif some other condition, then execute some other code.
- else if none of the above conditions are true , then execute some other code
by default = if x: #it equates it to true
LOOPS
The variable name defining the iterable can be anything .
FOR LOOP
mylist=[1,2,3,4,5,6,7]for num in mylist: if num%2==0: print(num) else print(f’Odd Number: {num}’)for_ in ’Hello: print(‘cool!’)will print cool 5 times
tuple and packing
mylist=[(1,2),(3,4)] 1. for item in mylist: print(item)2.for a,b in mylist: print(a) print(b)
For dictionaryd={‘k1’:1,‘k2’:2}1.for value in d.items(): print(value)#by default we iterate through keys.
WHILE LOOP
it keeps on iterating , until the condition is verified.
x=0while x<5: print(f’value of x is{x}’) x+=1
Three important statements
- break : breaks out of the loop
- continue :goes to the top of the loop
- pass:does nothing at all .It may act as a place holder to avoid syntax error due to indentation .
x=[1,2,3]for item in x: pass#if pass is not used it causes an EOF error