2. while statements
Infinite loop and break
Finishing iterations with continue
Definite loops using for
Loop Pattern
Counting and Summing loops
Maximum and Minimum loops
Iteration
3. The while Statement
Syntax:
while condition:
Statement 1
Statement 2
…..
Statement N
Statements after while
while: keyword
conditions will be evaluated and leads True or False
if True Statements will be executed else exits.
4. Eg:
1. n=1
while n<=5:
print(n)
n=n+1
print("Over")
2. n=5
while n>=0:
print(n)
n=n-1
print("Exit")
5. Loop execute infinite number of times.
Eg:
n=1
while True:
print(n)
n=n+1
Above program, loop condition is True, so it will never exits.
If we want to come out from the loop, we use break.
Eg:
n=1
while True:
print(n)
n=n+1
break
Infinite Loops, break and continue
6. Eg:
1. while True:
x=int(input("Enter a Number:"))
if x>=0:
print("You have entered a positive number. The number is:",x)
else:
print("You have entered a negative number")
2. while True:
x=int(input("Enter a Number:"))
if x>=0:
print("You have entered a positive number. The number is:",x)
else:
print("You have entered a negative number")
break
8. Move to next iterations , use continue statement.
Eg:
sum=0
count=0
while True:
x= int (input ("Enter a Number:"))
if x%2==0:
continue
else:
sum=sum+x
count=count+1
if count==5:
break
print("Sum=",sum)
continue statement
10. Syntax of for loop:
for var in list/sequence:
Statement 1
Statement 2
…..
Statement N
Statements after for loop
for and in are keywords
list/ sequence is a set of elements on which the loop iterates
statements constitutes the body of loop
11. Eg:
names=['Ram','Shyam','Raj']
for x in names:
print("Happy New Year",x)
print('Done!')
List is an important data type.
Can take elements of different types.
Elements enclosed within square brackets.
Elements can be extracted using index.
If there are fixed set of numbers to iterate in a for loop, we can use range()
12. range(start, end, steps)
Start: starting values
End: ending values but excluding ending value
Steps: increment/ decrement [default value is 1]
1. for i in range(5):
print(i,end='t')
2. for i in range(5,0,-1):
print(i,end='t')
3. for i in range(0,10,2):
print(i,end='t')
13. while and for loop used to go through a list of items and check max or min data values.
1. Initialize one/more variables before loop starts.
2. Perform computation
3. Look result
Counting and Summing Loops:
count=0
for i in [4,-2,41,34,25]:
count=count+1 #COUNT
print("Count=",count)
total=0
for i in [4,-2,41,34,25]:
total=total+I #SUMMATION
print("Total=",total)
Loop Patterns
14. big=None
print("Before Loop:",big)
for x in [12,0,21,-3]:
if big is None or x>big: #MAXIMUM
big=x
print("Itearation Variable:",x,'Big',big)
print("Biggest:",big)
small=None
print("Before Loop:",small)
for x in [12,0,21,-3]:
if small is None or x<small: #MINIMUM
small=x
print("Iteration Variable:",x,'Small',small)
print("Smallest:",small)