For-Loop - in Python
For-Loop - in Python
for i in range/sequencee:
statement 1
statement 2
statement n
======================
for num in range(10):
print(num)
=============
sum = 0
for i in range(2, 22, 2):
sum = sum + i
print(sum)
# output 110
=======================
numbers = [1, 2, 3, 4, 5]
# iterate over each element in list num
for i in numbers:
# ** exponent operator
square = i ** 2
print("Square of:", i, "is:", square)
====================
xample: Calculate the average of list of numbers
# definite iteration
# run loop 5 times because list contains 5 items
sum = 0
for i in numbers:
sum = sum + i
list_size = len(numbers)
average = sum / list_size
print(average)
===============================
name = "medam"
count = 0
for char in name:
if char != 'm':
continue
else:
count = count + 1
numbers = [1, 2, 3, 4]
for i in numbers[::-1]:
print(i)
===========================
# outer loop
for i in range(1, 6):
print('Multiplication table of:', i)
count = 1
# inner loop to print multiplication table of current number
while count < 11:
print(i * count, end=' ')
count = count + 1
print('\n')
==============
Printing the elements of the list with its index number using the range()
function
numbers = [1, 2, 4, 6, 8]
size = len(numbers)
for i in range(size):
print('Index:', i, " ", 'Value:', numbers[i])
===============
Access all characters of a string
name = "hello"
for i in name:
print(i, end=' ')
============
Iterate over words in a sentence using the split() function.
sent = "Remember, Red, hope is a good thing, maybe the best of things, and no good
thing ever dies"
# split on whitespace
for word in sent.split():
print(word)
==================================
Iterate over a list
numbers = [2, 3, 5, 6, 7]
for num in numbers:
print(num)
=========
li=[1,2,3]
for i in li:
print(i)
#range(stop)
for item in range(10):
print(item)
#range(start , stop)
for item in range(5,16):
print(item)
#range(10)
mylist =['apple','mango','banana']
for i in mylist:
print(i)
#ragne(start,stop,increment/decrement)
for x in range(2,10,3):
print(x)
#ragne(start,stop,decrement)
for x in range(20,1,-1):
print(x)
#for with break
for x in range(2,100):
print( "for loop in",x)
if (x==50):
break
print(x)
#for with continue
for x in range(2,10):
print("we are in for loop",x)
if(x==5):
continue
print(x)
for a in range(2,6):
print(a)
else:
print("hello we are at else")