6 – Decision and Looping Statements

DECISION STATEMENTS:

Decision statements are to execute instructions only if the conditions are met. Python allows three decision making statements. They are,

  1. If Statement
  2. If-else Statement
  3. Nested if Statement

IF STATEMENT

If statement executes the instructions only if the condition is met, else it will ignore it.

1
2
3
4
5
6
7
8
>>> a=20
>>> if(a==20):
	print "No is correct"
 
 
No is correct
>>> if(a==30):
	print "No is correct"

IF-ELSE STATEMENT

If-else statement executes the instructions under if block if the condition is met, else instructions under else block, will be executed.

1
2
3
4
5
a=10
if(a==10):
    print "No is correct"
else:
    print "No is Wrong"
OUTPUT
1
2
3
>>> 
No is correct
>>>

NESTED-IF STATEMENT

1
2
3
4
5
6
7
8
9
a=10
if(a==10):
    print "No is 10"
elif(a==20):
    print "No is 20"
elif(a==30):
    print  "No is 30"
else:
    print "Enter no 10,20,30"
OUTPUT
1
2
3
>>> 
No is 10
>>>

Nested-if checks for series of conditions using elif Statement.

LOOPS:

The loops used in python language are while, for and nested loop which is the combination of all loops

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
30
31
32
33
34
35
36
37
38
39
40
41
<<<#For Loop
for i in range(5):
	print i
 
 
0
1
2
3
4
<<<
<<<#While loop
>>> i=0
>>> while(i<5):
	print i
	i=i+1
 
 
0
1
2
3
4
<<<
<<<#Nested Loop
>>> i=0
>>> while(1):
	for j in range(2):
		print j
	if i==2:
		break
	i=i+1
 
 
0
1
0
1
0
1
>>>

LOOPING STATEMENT:

Looping statements used in python are break and continue. Break statement is used to exit the loop where continue statement is used to continue the next iteration skipping the instruction below it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>#Break Statement
>>> for i in range(5):
	print i
	if(i==3):
		break
 
 
0
1
2
3
>>>#Continue Statement
>>> for i in range(5):
	if(i==3):
		continue
	print i
 
 
0
1
2
4
>>>
THANK YOU
SHARE THIS!!!

Gowtham S

Gowtham is a programming enthusiast. His field of interest includes Arduino, NodeMCU, Raspberry Pi, and Python. To know more about him visit https://mybtechprojects.tech/about-us/.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.