0% found this document useful (0 votes)
14 views17 pages

DAY 8 Control - Flow - Ipynb - Colab

Python

Uploaded by

vaishnaviware005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
14 views17 pages

DAY 8 Control - Flow - Ipynb - Colab

Python

Uploaded by

vaishnaviware005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

Jake VanderPlas in “A Whirlwind Tour of Python” would say:

“Control flow is where the rubber really meets the road in programming.

a=10
a
10

control flow statements

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.

Python has three types of control structures:

1. Sequential - default mode


2. Selection - used for decisions and branching
3. Repetition - used for looping, i.e., repeating a piece of code multiple times.

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.

# this is the sequential statement


a=10
b=40
c=a+b
print("addition is :",c)
addition is : 50

2. Selection/Decision control statements

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.

Some Decision Control Statements are:

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.

A simple if only has one condition to check.

Here’s the syntax for the if statement


if expression:

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

pass statement in if loop

x=10
y=10
if x > y :

File "<ipython-input-4-5b91a4752af3>", line 3


if x > y :
^
SyntaxError: incomplete input

Next steps: Fix error

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

not keyword used in if loop

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

not operator in if statement

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.

# Here’s the syntax


if expression:
statements
else:
statements

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:

Nested if statements are an if statement inside another if statement.

#Here's the syntax


if condition:
if condition:
statements
else:
statements
else:
statements

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.

#Here's the syntax

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

check multiple conditions together with elif:

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

short hand if.....else

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

Start coding or generate with AI.

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 pass statement

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

A repetition statement is used to repeat a group(block) of programming instructions.

In Python, we generally have two loops/repetitive statements:

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.

Here’s the syntax for the for statement:

for target in iterable:

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)

NameError: name 'replace' is not defined


for i in [2,3,5,7] :
print(i,end=' ')
2 3 5 7

keyboard_arrow_down Notice the simplicity of the for loop:


we specify the variable we want to use, the sequence we want to loop over, and use the "in" operator to link them together in an intuitive and
readable way.

More precisely, the object to the right of the "in" can be any Python iterator.

An iterator can be thought of as a generalized sequence.

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 can take one, two, or three parameters.

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)

start: Starting number of the sequence.by default 0

stop: Generate numbers up to, but not including this number.

step: Difference between each number in the sequence.by default 1

ls=[10, 20, 30, 40]


for i in ls:
print(i,end=' ')
10 20 30 40

# 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.

Range objects can also have more complicated values:


#range from 2 to 10 range(start,stop)
list(range(3,9))
[3, 4, 5, 6, 7, 8]

# range from 0 to 10 by 2 (start,stop,step) 0 1 2 3 4 5 6 7 8 9


1 2 1 2 1 2 1 2 1 2
list(range(0, 10, 2))
[0, 2, 4, 6, 8]

# Measure some strings:


words = ['cat', 'window','trinity']
for w in words:
print(w, len(w))
cat 3
window 6
trinity 7

index number with value

a = ['Mary', 'had', 'a', 'little', 'dsib'] # i index a[i] value


for i in range(len(a)):
print(i, a[i])

0 Mary
1 had
2 a
3 little
4 dsib

reverse the range of particular numbers given by user

for i in range(5, 0, -1):


print (i)
5
4
3
2
1

for i in range(10, 2, -2):


print (i)
10
8
6
4

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

else in for loop

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

Double-click (or enter) to edit

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.

This continues until the expression becomes false.


keyboard_arrow_down Here’s the syntax for the while statement:
while expression:

statement(s)

i=0
while i==1:
print("hello")

while loop: its intentionally infinite loop

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

*break and continue: *

There are two useful statements that can be used within loops to fine-tune how they are executed:

The break statement breaks-out of the loop entirely

The continue statement skips the remainder of the current loop, and goes to the next iteration

These can be used in both for and while loops.


print only odd number in particular rang using the continue keyword

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

for num in range(2, 10): # (start,stop) 2 3 4 5 6 7 8 9


if num % 2 == 0:
print("Found an even number", num)
else:
print("Found an odd number", num)
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9

break escapes the current loop, and moves on after it.

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.

for i in [0, 1]: #0 a 1 b 1 1 a 1 b 1


for j in ["a","b"]:
print("1")
print("2")
1
1
1
1
2

for i in [0, 1]:


for j in ["a","b"]:
print("1")
print("2")
1
2
1
2
1
2
1
2

# 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 = ''

You might also like