Post Top Ad

Tuesday, December 11, 2018

The For Loop in Python

for loop is used for iterating over a sequence


Example : 

fruits = ["apple""banana""cherry"]
for in fruits:
  print(x)


Note: The for loop does not require an indexing variable to set beforehand.

Looping Through a String

for x in "banana":
  print(x)

The break Statement

Exit the loop when x is "apple":


fruits = ["orange""apple""cherry"]
for x in fruits:
  print(x) 
  if x == "apple":
    break



The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue with the next:



fruits = ["orange""apple""cherry"]
for x in fruits:
  if x == "apple":
    continue
  print(x)



The range() Function

To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

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



Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
  print(x)
else:
  print("Finally finished!")

Nested Loops

A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":


adj = ["red""big""tasty"]
fruits = ["apple""banana""cherry"]

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




No comments:

Post a Comment