Thursday, 26 March 2020

For loops and some exercises


For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages.
for var in iterable
# statements 
In Python, iterable means an object can be used in iteration. 

Cities = ["London ", "Leeds ", "Birmingham "]
for x in fruits:
  print(x) 
 
Out put 
London 
Leeds
Birmingham 

The range() Function For example, if you wanted to iterate through the values from 0 to 4, you could simply do this 

for x in range(4):
  print(x) 

Out put 
0
1
2
3
4

Using the start parameter:
for x in range(2, 6):
 print(x)

Out put
2
3
4
5
6
The  range()  function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2,10,3)
for x in range(2,10,3):
  print(x)
Out put
2
5
8

for x in range(6):
  print(x)
else:
  print("Welcome to python world!")

Out put
Welcome to python world!
Nested for loop


num= ["1""2"]
fruits = ["apple""banana"]

for x in num:
  for y in fruits:
    print(x, y)

out put
1 apple
1 banana
2 apple
2 banana








No comments:

Post a Comment