Professional Documents
Culture Documents
Introduction:
Statements are the instructions given to the computer to perform some tasks.
Types of Statements:
1. Empty Statement
2. Simple Statement
3. Compound Statement
Empty statement:
The simplest statement is the empty statement i.e., a statement which does
nothing. In Python an empty statement is pass statement.
Syntax:
pass
Simple statement:
ex:
Compound Statement:
Syntax:
• Here, Header line starts with the keyword and ends at colon (:).
• The body consists of more than one simple Python statements or compound
statements.
ex:
a=20
b=10
print(“a is biggest”)
print(“b is biggest”)
Sequence:
The Sequence construct means the statements are being executed sequentially.
Till the time a condition is True, a set-of-statements are repeated again and
again. Once the condition becomes False, the repetition stops.
The if statement:
Syntax:
if <condition>:
statement(s)
Flowchart:
ex:
a=20
b=10
if a>b: # if the condition evaluates True, then it prints the statement, otherwise exits
print(“a is biggest”)
The if-else statement:
Syntax:
if <condition>:
else:
Flowchart:
ex:
a=20
b=10
if a>b: # if test evaluates True, the True statement execute, otherwise False statement
else:
Nested if-else:
a=int(input(“enter a value’))
b=int(input(“enter a value’))
c=int(input(“enter a value’))
if a>b:
if a>c:
print(“a is biggest”)
else:
print(“c is biggest”)
else:
if b>c:
print(“b is biggest”)
else:
print(“c is biggest”)
The if-elif statement:
if(conditional expression):
statement(s)
elif(conditional expression):
statement(s)
if(conditional expression):
statement(s)
elif(conditional expression):
statement(s)
else:
statement(s)
ex:
if ch==’+’:
result=a+b
elif ch==’-‘:
result=a-b
elif ch==’*‘:
result=a*b
elif ch==’/‘:
result=a/b
elif ch==’%‘:
result=a%b
else:
print(“Invalid operator”)
print(a,ch,b,”=”,result)
Iteration Statements (Loops):
Iteration statements (loop) are used to execute a block of statements as long as
the condition is true. Loops statements are used when we need to run same code
again and again.
1. While Loop
2. For Loop
1. While Loop:
If the condition becomes false, the control will come out of the loop.
Syntax:
while (condition):
statement
[statements]
Flow chart:
e.g.
x=1
print(x)
x=x+1
3rd iteration:while(3<=4)
Output:
x=1
x=x+1
else:
Output:
2. For Loop:
It is used to iterate over items of any sequence, such as a list or a string.
2. stop: Generate numbers up to, but not including this number (n-1).
ex:
>>> 3 in [1,2,3,4,5]
True
>>> 5 not in [1,2,3,4]
True
Syntax:
statements
e.g. 1
for i in range(3,5):
print(i)
Output :
e.g. 2
for i in range(5,3,-1):
print(i)
Output:
4
For Loop With Else:
e.g.
print(i)
print("No Break")
Output:
No Break
But in a nested loop, the inner loop must terminate before the outer loop.
e.g. 1
for j in range(1,i):
Output:
* *
* * *
* * * *
* * * * *
e.g. 2
for i in range(1,3):
for j in range(1,11):
k=i*j
print()
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20