0% found this document useful (0 votes)
100 views

02.conditional & Control Flow Statements - Jupyter Notebook

The document discusses different types of control flow statements in Python programming including sequential, selection, and iterative control structures. Selection control structures include conditional statements like if, elif, and else that allow for decision making. Iterative control structures include for and while loops that repeat a block of code as long as a condition is true. The document provides examples of using if/else statements, nested if statements, for loops, range() functions, and using else blocks with for loops.

Uploaded by

kasarla rakesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

02.conditional & Control Flow Statements - Jupyter Notebook

The document discusses different types of control flow statements in Python programming including sequential, selection, and iterative control structures. Selection control structures include conditional statements like if, elif, and else that allow for decision making. Iterative control structures include for and while loops that repeat a block of code as long as a condition is true. The document provides examples of using if/else statements, nested if statements, for loops, range() functions, and using else blocks with for loops.

Uploaded by

kasarla rakesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

2.

Conditional & Control


Flow Statements(Control
Structures)
1. Decision making or Conditional statements (if, else, and elif)
2. loops or control statements (for & while)
3. User Input

PYTHON Control Structures:


In PYTHON Programming Control Structures are classified into:

1. Sequential Control Structures


2. Selection Control Structures
3. Iterative Control Structures

Control_Flow Pic:

1. Sequential Control Structures:


It gets executes the lines of code in sequential order.
In [1]: 1 print("Line1")
2 print("Line2")
3 print("Line3")

Line1
Line2
Line3

In [2]: 1 print("Line1");print("Line2");print("Line3")

Line1
Line2
Line3

2. Selection Control Structures: (Conditional Control


Statements):
It is popularly known as Python Decision Making statments.
Python programming language provides following types of decision making statements.

1. if statement ====================>One-Way Decisions


2. if .. else statement ============>Two-Way Decisions
3. if .. elif .. else statement ====>Multi-Way Decisions
4. Nested if .. else ===============>inner Decisions
5. Negative Conditions =============>Using Member-ship operators

Python 'if' Statement:-

It executes a set of statements conditionally, based on the value of a logical expression.

In [1]: 1 n = 101
2 if n>100:
3 print("This is more then 100")
4 print("THis always executes")

This is more then 100


THis always executes

In [2]: 1 n = 10
2 if n>100:
3 print("This is more then 100")
4 print("THis always executes")

THis always executes

if .. else Statement:-
An else statement can be combined with an if statement. An else statement contains the block

In [6]: 1 n = 101
2 if n>100:
3 print("This is more then 100")
4 else:
5 print("This is less then 100")
6 print("THis always executes")

This is more then 100


THis always executes

In [7]: 1 n = 10
2 if n>100:
3 print("This is more then 100")
4 else:
5 print("This is less then 100")
6 print("THis always executes")

This is less then 100


THis always executes

Python if...elif...else:-

The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.

In [21]: 1 n = 0
2 if n>100:
3 print("This is more then 100")
4 elif n<0:
5 print("This is negative number")
6 elif n>1000:
7 print("This is more then 1000")
8 else:
9 print("Value is zero")

Value is zero

Nested if .. else statement;-

In general nested if-else statement is used when we want to check more than one conditions.
Conditions are executed from top to bottom and check each condition whether it evaluates to
true or not.
In [23]: 1 num = int(input("Enter a number: "))
2 if num >= 0:
3 if (num == 0):
4 print("ZERO")
5 else:
6 print("Positive number")
7 else:
8 print("Negative number")

Enter a number: 0
ZERO

In [9]: 1 # Election age calculating


2 age = 20
3 identity_card = "Yes"
4 if age>18:
5 if identity_card == 'Yes':
6 print("He can vote")
7 else:
8 print("he can't vote as he dont have identity_card")
9 else:
10 print("He can't vote as his age is less then 18...")

He can vote

In [10]: 1 # Election age calculating


2 age = 17
3 identity_card = "Yes"
4 if age>18:
5 if identity_card == 'Yes':
6 print("He can vote")
7 else:
8 print("he can't vote as he dont have identity_card")
9 else:
10 print("He can't vote as his age is less then 18...")

He can't vote as his age is less then 18...

In [11]: 1 # Election age calculating


2 age = 23
3 identity_card = "No"
4 if age>18:
5 if identity_card == 'Yes':
6 print("He can vote")
7 else:
8 print("he can't vote as he dont have identity_card")
9 else:
10 print("He can't vote as his age is less then 18...")

he can't vote as he dont have identity_card

Negative Conditions in PYTHON:


If a condition is true the not operator is used to reverse the logical state, then logical not
operator will make it false.

In [24]: 1 x = int(input("Enter Any Number: "))


2 print(x)
3 if not x == 50:
4 print('the value of x different from 50')
5 else:
6 print('the value of x is equal to 50')

Enter Any Number: 50


50
the value of x is equal to 50

3. Iterative Control Structures (Python Loops):

What is a Loop?
A loop is a sequence of instructions that is continually repeated until a certain condition is
reached.

Why Loop?
In a loop structure, the loop asks a question. If the answer requires an action, it is executed.
The same question is asked again and again until no further action is required. Each time the
question is asked is called an iteration.

TYPES OF LOOPS in PYTHON:


1. for .
2. while.
3. nested loops.
4. break and continue (Loop Control Statements)

For loop in python:


It is used to iterate over the items of any sequence including the Python list, string, tuple etc.

In [27]: 1 for char in "PYTHON":


2 print("The Character is: ",char)

The Character is: P


The Character is: Y
The Character is: T
The Character is: H
The Character is: O
The Character is: N
How for loop work :

In [31]: 1 s = "PYTHON"
2 s_iter = iter(s)
3 print(next(s_iter))
4 print(next(s_iter))
5 print(next(s_iter))
6 print(next(s_iter))
7 print(next(s_iter))
8 print(next(s_iter))

P
Y
T
H
O
N

In [34]: 1 primes = [2, 3, 5, 7]


2 for prime in primes:
3 print(prime)

2
3
5
7

range() and xrange() functions in PYTHON:


range() – This returns a list of numbers created using range() function.
xrange() – This function returns the generator object that can be used to display numbers
only by looping.

xrange() renamed as range() in Python-3.0

Range Function
It generates lists containing arithmetic progression. It returns a list of consecutive integers. The
function has one, two or three parameters where last two parameters are optional. It is widely
used in for loops.

3 variations of range() function:

range(stop) - Starts from O till (stop - 1)


range(start,stop) - Ends at (stop - 1)
range(start,stop,step) - Step can not be 0, default is 1
In [17]: 1 rg = range(1,10)
2 print(rg)
3 print(list(rg))
4 print(type(rg))

range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'range'>

In [38]: 1 for i in range(10):


2 print(i)

0
1
2
3
4
5
6
7
8
9

In [5]: 1 print(list(range(10)))
2 print(list(range(10,30)))
3 print(list(range(10,30,5)))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29]
[10, 15, 20, 25]

for loop with else clause


A for loop can have an optional else block as well.
The else part is executed if the items in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.

In [8]: 1 # for with else and no break


2 for i in range(5):
3 print(i)
4 else:
5 print("No items left in list")

0
1
2
3
4
No items left in list
In [9]: 1 # for with else with break
2 for i in range(5):
3 if i == 4:
4 break;
5 print(i)
6 else:
7 print("No items left in list")

0
1
2
3

NOTE:

if we stop the loop, say with a break statement, then the else suite will not be executed

break
To break out from a loop, you can use the keyword "break".

In [10]: 1 for x in "PYTHON":


2 if(x=='O'):
3 break
4 print(x)
5 else:
6 print("Loop Completed")

P
Y
T
H

In [11]: 1 for x in "PYTHON":


2 if(x=='R'):
3 break
4 print(x)
5 else:
6 print("Loop Completed")
7 ​

P
Y
T
H
O
N
Loop Completed
Continue
The continue statement is used to tell Python to skip the rest of the statements in the current
loop block and to continue to the next iteration of the loop.

In [19]: 1 for i in range(6):


2 if i==3:
3 continue
4 print(i)
5 else:
6 print("Else will execute eveytime in continue")

0
1
2
4
5
Else will execute eveytime in continue

In [17]: 1 for i in range(6):


2 print(i)
3 if i==3:
4 continue
5 else:
6 print("Else will execute eveytime in continue")

0
1
2
3
4
5
Else will execute eveytime in continue

while Loop Statements:


while Loop is used to execute number of statements or body till the condition passed in while is
true. Once the condition is false, the control will come out of the loop.

In [18]: 1 x = 0
2 while x<=5:
3 print(x)
4 x+=1

0
1
2
3
4
5
while and else statement
There is a structural similarity between while and else statement. Both have a block of
statement(s) which is only executed when the condition is true.

In [19]: 1 x=1
2 while x<=5:
3 print(x)
4 x=x+1
5 else:
6 print("loop Finished")
7 ​

1
2
3
4
5
loop Finished

In [20]: 1 a=10
2 while a>0:
3 print("Value of a is",a)
4 a=a-2
5 else:
6 print("Loop is Completed")
7 ​

Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed

In [2]: 1 x = 0
2 while x<6:
3 print(x)
4 x+=1
5 else:
6 print("While completed")

0
1
2
3
4
5
While completed
In [3]: 1 x = 0
2 while x<6:
3 if x == 3:
4 break;
5 print(x)
6 x+=1
7 else:
8 print("While completed")

0
1
2

In [ ]: 1 # This will have infinte loops as we have mentioned continue before incre
2 # when poniter reaches 3 it will keep executing continue there is no incr
3 x = 0
4 while x<6:
5 if x == 3:
6 continue;
7 print(x)
8 x+=1
9 else:
10 print("While completed")

0
1
2

In [1]: 1 x = 0
2 while x<6:
3 x+=1
4 if x == 3:
5 continue;
6 print(x)
7 else:
8 print("While completed")

1
2
4
5
6
While completed

Python nested loops


• Python programming language allows to use one loop inside another loop.

Syntax
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
f [ d it ti i bl ] i [ t dl ] #N t dl
In [26]: 1 for i in range(5):
2 for j in range(5):
3 print(i+j,end=" ")
4 print()

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

Printing patterens in python:

In [27]: 1 pattern=int(input("Enter Number of Rows: "))


2 for i in range(1, pattern+1):
3 for j in range(1,i+1):
4 print("*",end=" ")
5 print()

Enter Number of Rows: 5


*
* *
* * *
* * * *
* * * * *

In [31]: 1 pattern=int(input("Enter Number of rows: "))


2 for i in range(pattern,0,-1):
3 for j in range(0,i):
4 print("*",end="")
5 print()

Enter Number of rows: 5


*****
****
***
**
*

In [32]: 1 pattern=int(input("Enter Number of rows: "))


2 for i in range(1,pattern+1):
3 for j in range(1,pattern+2-i):
4 print("*",end="")
5 print()

Enter Number of rows: 5


*****
****
***
**
*
In [30]: 1 pattern=int(input("Enter Number of rows: "))
2 for i in range(0,pattern):
3 for j in range(0,pattern-i-1):
4 print(end=" ")
5 for j in range(0,i+1):
6 print("*",end=" ")
7 print()

Enter Number of rows: 5


*
* *
* * *
* * * *
* * * * *

In [33]: 1 pattern=int(input("Enter Number of rows: "))


2 for i in range(pattern,0,-1):
3 for j in range(0,pattern-i):
4 print(end=" ")
5 for j in range(0,i):
6 print("*",end=" ")
7 print()

Enter Number of rows: 5


* * * * *
* * * *
* * *
* *
*

PASS KEYWORD
It is used when a statement is required syntactically but you do not want any command or code
to execute.
Why Pass?

It is an empty statement
It is null statement
It results into no operation (NOP)

In [35]: 1 for i in "PYTHON":


2

Input In [35]

^
IndentationError: expected an indented block
In [36]: 1 for i in "PYTHON":
2 pass

Note:
Above we can understand that when we use pass keyword there is no error.

User Input
Python allows for user input.
That means we are able to ask the user for input.
The method is a bit different in Python 3.6 than Python 2.7.
Python 3.6 uses the input() method.
Python 2.7 uses the raw_input() method.

In [1]: 1 name = input("Enter your name:")


2 print(name)

Enter your name:Rakesh


Rakesh

In [2]: 1 age = input("Enter your age: ")


2 print(type(age))

Enter your age: 30


<class 'str'>

In [19]: 1 ### Taking some charcter as in put


2 mobile = input("Enter your number : ")[0:10]
3 print(mobile,len(mobile))

Enter your number : 11111222223333344444


1111122222 10

Evaluating expression

In [20]: 1 res = input("Enter expression : ")


2 print(res)

Enter expression : 2 + 3 + 5
2 + 3 + 5
In [21]: 1 res = eval(input("Enter expression : "))
2 print(res)

Enter expression : 2 + 3 + 5
10

How to take input from cmd to python

Create a py file with below code:

Trying to running now

Changing code like below now:

Output:

You might also like