DAY 8 Control - Flow - Ipynb - Colab
DAY 8 Control - Flow - Ipynb - Colab
“Control flow is where the rubber really meets the road in programming.
a=10
a
10
A program’s control flow is the order in which the program’s code executes.
The control flow of a Python program is regulated by conditional statements, loops, and function calls.
1. Sequential
Sequential statements are a set of statements whose execution process happens in a sequence.
The problem with sequential statements is that if the logic has broken in any one of the lines, then the complete source code execution will
break.
In Python, the selection statements are also known as Decision control statements or branching statements.
The selection statement allows a program to test several conditions and execute instructions based on which condition is true.
Simple if
if-else
nested if
if-elif-else
Simple if:
If statements are control flow statements that help us to run a particular code, but only when a certain condition is met or satisfied.
statements
indentation Python relies on indentation (whitespace at the beginning of line) to define scope in the code. other programming languages often
use curly - brackets for this purpose.
x=20
y=10
if x > y :
print(" X is bigger ")
print("hello")
X is bigger
hello
x=20
y=10
if x>y:
print("x is big")
x is big
x=10
y=10
if x > y :
x=10
y=10
if x > y :
pass
x=10
y=20
if x<y:
print("hello")
hello
a=10
b=10
if a==b:
print("a is equal to b")
a is equal to b
a=20
b=30
if not a>b:
print("a is equal to b")
a is equal to b
a=10
b=20
if a!=b:
print("a is not equal to b")
a is not equal to b
x=3
if x>10:
print("x is big.")
if x<= 10:
print("x is small.")
x is small.
x=10
if x<5:
print("x is smaller")
if x>5:
print("x is bigger")
x is bigger
#n = 10
if 10 % 2 == 0:
print("n is an even number")
n is an even number
By using Not keyword we can change the meaning of the expressions, moreover we can invert an expression.
mark = 100
if not (mark == 100):
print("mark is not 100")
else:
print("mark is 100")
mark is 100
mark = 100
if (mark != 100):
print("mark is not 100")
else:
print("mark is 100")
mark is 100
mark=100
if not mark==100:
print("mark not equal to 100")
else:
print("mark equal to 100")
mark equal to 100
in operator in if statement
color = ['Red','Blue','Green']
selColor = "purple"
if selColor in color:
print("Red is in the list")
p ( )
else:
print("Not in the list")
Not in the list
if-else:
The if-else statement evaluates the condition and will execute the body of if, if the test condition is True, but if the condition is False, then the
body of else is executed.
The else keyword cataches anything which isn't caught by the preceding conditios.
x=10
y=20
if x > y :
print(" X is bigger ")
else :
print(" Y is bigger ")
Y is bigger
x=20
y=40
if x<y:
print("x is smaller")
else:
print("x is bigger")
x is smaller
a=10
b=20
if a!=b:
print("a is not equal to b")
else :
print("a is equal to b")
a is not equal to b
n = 7
if n % 2 == 0:
print("n is even")
else:
print("n is odd")
n is odd
nested if:
elif
elif keyword is pythons way of saying " if the previous conditions were not true, then try this condition".
a=10O
b=20
if a==b:
print("a is equal to b")
elif a!=b :
print("a is not equal to b")
a is not equal to b
x=20
y=40
if x>y:
print("x is bigger")
elif x<y:
print("x is smaller")
x is smaller
mark = 55
if mark > 50:
if mark >= 80:
print ("You got A Grade !!")
elif mark >=60 and mark < 80 :
print ("You got B Grade !!")
else:
print ("You got C Grade !!")
else:
print("you are failed")
You got C Grade !!
a = 1511
b = 1000
c = 8000
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big")
elif b > c:
print("b value is big")
else:
print("c is big")
c value is big
keyboard_arrow_down if-elif-else:
The if-elif-else statement is used to conditionally execute a statement or a block of statements.
if expression:
statements
elif expression:
statements
else:
statements
a=40
b=50
if a>b:
print ("a is bigger")
elif a<b:
print("a is smaller")
else:
print("both are equal")
a is smaller
x=60
y=60
if x==y:
print("x is equal to y")
elif x<y:
print("x is smaller")
else:
print("x is bigger")
x is equal to y
a=20
b=20
if a>b:
print("a is greater than b")
elif b>a:
print("b is greater than a")
else:
print("both are equal")
both are equal
x=300
if x > 500 :
print(" X is greater than 500 ")
elif x < 500 :
print(" X is less than 500 ")
elif x == 500 :
print(" X is 500 ")
else :
print(" X is not a number ")
X is less than 500
x=3
if x>10:
print("x is big.")
elif x<10:
print("x is small.")
else:
print("x is not positive.")
x is small.
x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")
x is greater than y
x = 6
if x == 0:
print(x, "is zero")
elif x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is unlike anything I've ever seen...")
6 is positive
short hand if
if you have only one statement to execute,you can put it on the same line as the if statement.
a=40
b=50
if a<b:print("a is smaller than b")
a is smaller than b
If you have only one statement to execute, one for if, and one for else, you can put it all on the same line.
a=10
b=30
print("a is less than b") if a<b else ("a is greater than b")
a is less than b
And
The and keyword is a logical operator, and is used to combine conditional statement.
a=80
b=70
if a<b and b>a :
print("b is greater than a")
a=20
b=10
if a>b and b<a :
print("a is greater than b")
a is greater than b
Or
The or keyword is a logical operator, and is used to combine conditional statements. TRue when one condition is true out of two
a=20
b=10
if a>b or b>a :
print("a is greater than b")
a is greater than b
The if statements cannot be empty, but if you for some reason have an if statement with no content,put in the pass statement to avoid getting
an error.
a=200
b=100
if a>b:
File "<ipython-input-32-deebb3d87be8>", line 3
if a>b:
^
SyntaxError: incomplete input
a=200
b=100
if a>b:
pass
3. Repetition
for loop
while loop
for loop:
A for loop is used to iterate over a sequence that is either a list, tuple, dictionary, or a set. We can execute a set of statements once for each
item in a list, tuple, or dictionary.
statement(s)
import keyword
keyword.kwlist
['False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield']
color=['red','green','yellow','pinck','white']
for samarth in color:
print(samarth)
red
green
yellow
pinck
white
directions = ['North','East','West','South']
for pole in directions:
print(pole)
North
East
West
South
directions = ['North','East','West','South']
for pole in directions:
print(pole,end=' ')
North East West South
str = ("Python")
for ch in str:
print(ch,end='=')
P=y=t=h=o=n=
s=[2, 3, 5, 7]
for N in s:
print(N,end=' ') # print all on same line
2 3 5 7
help(replace)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-a1656cf33f70> in <cell line: 1>()
----> 1 help(replace)
More precisely, the object to the right of the "in" can be any Python iterator.
For example, one of the most commonly-used iterators in Python is the range object, which generates a sequence of numbers:
The range function in for loop is actually a very powerful mechanism when it comes to creating sequences of integers.
It returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound , possibly in
increments (steps) of some other number (one, by default).
Note for Python 3 users: There are no separate range and xrange() functions in Python 3, there is just range, which follows the design of Python
2's xrange.
range(stop)
range(start,stop)
range(start,stop,step)
# 0 1 2 3 4
lst=[10,20,30,40]
for i in range(len(lst)):
range(4)
print(lst[i],end=' ')
10 20 30 40
lst=[10,20,30,40]
for i in lst:
print(i,end=' ')
10 20 30 40
range(9)
range(0, 9)
for i in range(5):
print(i,end=' ')
0 1 2 3 4
Note that the range starts at zero by default, and that by convention the top of the range is not included in the output.
0 Mary
1 had
2 a
3 little
4 dsib
Break Statement
with the break statement we can stop the loop before it has looped through all the items.
fruits=["apple","bannana","kiwi","cherry","watermelon"]
for a in fruits:
if(a=="cherry"):
break
print(a)
apple
bannana
kiwi
Continue Statement
with the continue statement we can stop the current iteration of the loop and continue with the next.
fruits=["apple","bannana","cherry","pinapple"]
for s in fruits:
if(s=="cherry"):
continue
print(s)
apple
bannana
pinapple
The else keyword in a for loop specifies a block of code to be executed when the loop is finished.
animal=['lion','tiger','cow','dog']
for a in animal :
print(a)
else:
print("thank you")
lion
tiger
cow
dog
thank you
pass statement
for loops cannot be empty , but if you for some reason have a for loop with no content ,put in the pass statement to avoid getting an error
fruits=["apple","bannana","cherry"]
for s in fruits:
pass
fruits=["apple","bannana","cherry"]
for s in fruits:
File "<ipython-input-2-de1edb360039>", line 2
for s in fruits:
^
SyntaxError: incomplete input
while loop:
In Python, while loops are used to execute a block of statements repeatedly until a given condition is satisfied.
Then, the expression is checked again and, if it is still true, the body is executed again.
statement(s)
i=0
while i==1:
print("hello")
i = 0
while i < 10:
print(i)
i += 1
0
1
2
3
4
5
6
7
8
9
m = 5
i = 0
while i < m:
print(i, end = " ")
i = i + 1
print("End")
0 1 2 3 4 End
range(6)
range(0, 6)
range(0,5)
range(0, 5)
i=1
while i<6:
print(i)
i+=1
else:
print("i is no longer than 6")
1
2
3
4
5
i is no longer than 6
There are two useful statements that can be used within loops to fine-tune how they are executed:
The continue statement skips the remainder of the current loop, and goes to the next iteration
for n in range(20):
# if the remainder of n / 2 is 0, skip the rest of the loop
if n % 2 == 0:
continue
print(n, end=' ')
1 3 5 7 9 11 13 15 17 19
x=0
while x < 50:
x+=10
if x==30:
continue
print (x)
print("Loop Over")
10
20
40
50
Loop Over
with the break statement we can stop the loop even if the while condition is true. For example
i=1
while i<10:
if(i==5):
break
print(i)
i+=1
1
2
3
4
i=1
while i<10:
if(i==5):
continue
print(i)
i+=1
1
2
3
4
x=10
while True:
print (x)
x+=2;
if x>20:
break
print("After Break")
10
12
14
16
18
20
After Break
for i in range(100):
if i==5:
break
print(i)
5
for i in range(100):
if i==5:
break
else:
print("Unable
White Space to find 5.")
print(i)
Python determines where a loop repeats itself by the indentation in the whitespace.
Everything
5 that is indented is part of the loop, the next entry that is not indented is not.
# 012345
s = 'python'
#reverse string
#print(s[::-1])
# without slicing
a = len(s) - 1 # 6-1 5
b = ''
while a>=0:
b += s[a] # b=b+s[a] ''+n n n+s[4] n+o no
a = a -1 # 4
print(b)
print(s[5])
nohtyp
n
s = 'python'
#reverse string
new = ''