Class 5
Class 5
Class 5 notes
+++++++++++++++++++++++
1. Conditional Statements
2. Looping Statements
** Conditional Statements **
****************************
Indentation
-----------
In Python {} are not available to define the body of conditional statement, functions, loop etc.
For define body we use 'indentation'
Syntax:
-------
if <condition>:
#statement
else:
#statement
Variable: a,b=10,20
if a<b:
print('a is less than b')
print('%d is less than %d' % (a, b))
else:
print('a is greater than b')
print('%d is greater than %d' % (a, b))
if <condition>:
#statement
elif <condition>:
#statement
else:
#statement
** Looping Statements **
************************
A loop statement allows us to execute a statement or group of statements multiple times.
Repitition work we do using loop.
range() syntax
--------------
range(start,stop,step)
Some example:
-------------
for x in range(10):
print(x)
for x in range(1,11):
print(x, end=" ")
for x in range(1,20,2):
print(x, end=" ")
for loop
--------
1) Print 1 to 10
for x in range(1,11):
print(x)
3)
1
22
333
4444
55555
4)
1
12
123
1234
12345
4)
5
44
333
2222
11111
start = 6
for row in range(1,6):
for col in range(0,row):
print(start-row, end=" ")
print()
5)
11111
2222
333
44
5
months = ["Jan","Feb","Mar","April","May","June"]
for key, value in enumerate (months):
print(key,value)
while Loop
----------
Using while loop we can execute a set of statements till condition is true.
Syntax:
-------
while <condition or expression>:
#body of loop
i=1
while i < 6:
print(i)
i += 1
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter