Python Programming - Control Structure
Python Programming - Control Structure
Grade XI
Informatics Practices
Python Programming
Simple if
•Syntax:
if expression:
statement(s)
next statement
•Remember to indent the statements in a block equally.
•This is because we don’t use curly braces to delimit blocks. Also, use
a colon(:) after the condition.
•If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) next statement is executed.
Example:
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
If-else statement
•Syntax:
if expression:
statement(s)
else:
statement(s)
•If the boolean expression evaluates to TRUE, then the block of
statement(s) inside the if statement is executed.
Example-1:
if 2<1:
print("2")
else:
print("1")
Nested If statement
•Syntax:
if expression:
statement(s)
if expression:
statement(s)
if expression:
statement(s)
a=1
b=2
if a==1:
if b==2:
print("a is 1 and b is 2")
if 2<1:
print("2")
elif 3<1:
print("3")
else:
print("1")
Functions
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#start value is given as 2
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
#step value is 5 and start value is 0
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
#step value is -1. Hence, decreasing #sequence is generated
>>> list(range(0, -9, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8]
The function range() is often used in for loops for generating a
sequence of numbers.
For Loop
While Loop
Syntax:
Initialization
While(condition):
statement(s)
incr/decr
•When the program control reaches the while loop, the condition is
checked. If the condition is true, the block of code under it is
executed.
Example:
a=3
while(a>0):
print(a)
a-=1
Output
3
2
1
This loop prints numbers from 3 to 1. In Python, a—wouldn’t work.
We use a-=1 for the same.
Syntax:
Initialization
While(condition): statement(s); incer/decr;
•>>> a=3