Monday 22 January 2024



1. for Loop:

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects. It has the following syntax:

for variable in iterable: # Code to be executed in each iteration
Here's a simple example:

fruits = ["apple", "banana", "cherry"
for fruit in fruits: 
This loop iterates over the list fruits, and in each iteration, the variable fruit takes on the value of the current element in the list.

2. while Loop:

The while loop is used to repeatedly execute a block of code as long as a given condition is true. It has the following syntax:

while condition: # Code to be executed as long as the condition is true

Here's an example:

count = 0 while count < 5
print(count) count += 1
This loop prints the values of count from 0 to 4. The loop continues to execute as long as the condition count < 5 is true.

Loop Control Statements:

Python provides two loop control statements that allow you to manipulate the flow of a loop:

break: Terminates the loop prematurely, and the program continues with the next statement after the loop.

continue: Skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration.

Iterating Over Sequences:

In Python, you often use loops to iterate over sequences like lists, strings, or ranges. The range() function is commonly used to generate a sequence of numbers for iteration.

for i in range(5): 

This prints the numbers from 0 to 4.

Loops are fundamental for creating efficient and flexible programs, and they play a crucial role in various programming tasks.

No comments:

Post a Comment

Mức thuế ở Úc từ 07/2024

Chính phủ Úc đã thay đổi các mức thuế suất cho thu nhập cá nhân và các mức thu nhập (được gọi là ‘ngưỡng’) áp dụng những thuế suất này. Việc...