Loops

Loops

Loops

Loops: 

In Python, loops are used to execute a block of code repeatedly. There are two main types of loops in Python: “for” loops and “while” loops.

For loops:

The “for” loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. The general syntax for a “for” loop is:

				
					for variable in sequence:
    # code to execute for each item in the sequence
				
			

Here, “variable” is a variable that is assigned the value of each item in the sequence, one at a time. The code  block inside the “for” loop is executed once for each item in the sequence.

For example, here’s how you can use a “for” loop to print each item in a list:

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

				
			

While loops:

The “while” loop is used to repeatedly execute a block of code as long as a certain condition is true. The general syntax for a “while” loop is:

				
					while condition:
    # code to execute while condition is True
				
			

Here, “condition” is any expression that evaluates to a boolean value (True or False). The code block inside the “while” loop is executed repeatedly as long as the condition is True.

For example, here’s how you can use a “while” loop to print the numbers from 1 to 5:

				
					i = 1
while i <= 5:
    print(i)
    i += 1
				
			

In this example, the variable “i” is initially set to 1, and the code block inside the “while” loop is executed as long as “i” is less than or equal to 5. The variable “i” is incremented by 1 each time the code block is executed, so the loop will eventually terminate after printing the numbers from 1 to 5.

In addition to “for” and “while” loops, there are also several other types of loops in Python, including nested loops and “break” and “continue” statements, which allow you to control the flow of the loop.

Join To Get Our Newsletter
Spread the love