While Loop and For Loop
Veröffentlicht 2024-07-16 21:50:42
0
9KB
In Python, while and for loops are fundamental constructs for repeated execution of code blocks. They serve different purposes, so understanding their strengths is crucial for writing efficient and readable code.
While Loop:
- Syntax:
Python
while condition:
# Code to execute as long as the condition is True
-
Functionality:
- The
whileloop repeatedly executes a block of code as long as a certain condition remainsTrue. - The condition is evaluated at the beginning of each loop iteration.
- If the condition becomes
False, the loop terminates.
- The
-
Example:
Python
count = 0
while count < 5:
print(f"Count: {count}")
count += 1 # Increment counter
This loop prints "Count:" followed by the current value of count five times. The loop continues as long as count is less than 5.
For Loop:
- Syntax:
Python
for item in iterable:
# Code to execute for each item in the iterable
-
Functionality:
- The
forloop iterates over elements in a sequence (like a list, tuple, or string) called an iterable. - In each iteration, the current element is assigned to the loop variable (
itemin this example). - The code block is executed for each element in the iterable.
- The
-
Example:
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}.")
This loop iterates over the fruits list. In each iteration, the current fruit (e.g., "apple") is assigned to fruit, and the message is printed.
Choosing the Right Loop:
- Use a
whileloop when you don't know the exact number of iterations beforehand, and the loop continues based on a condition. - Use a
forloop when you need to iterate over a sequence of elements in a known order. It's generally more concise and readable for this purpose.
Additional Considerations:
- You can use the
breakstatement to exit a loop prematurely. - The
continuestatement skips the current iteration and moves to the next one. forloops can sometimes be rewritten aswhileloops (and vice versa), but using the appropriate loop for the situation improves code clarity.
Suche
Kategorien
- Technology
- Ausbildung
- Business
- Music
- Got talent
- Film
- Politics
- Food
- Spiele
- Gardening
- Health
- Startseite
- Literature
- Networking
- Andere
- Party
- Religion
- Shopping
- Sports
- Theater
- Wellness
Mehr lesen
While Loop and For Loop
In Python, while and for loops are fundamental constructs for repeated execution of code blocks....
UMTA UCE PHYSICS PAPER 1 2024
UMTA UCE PHYSICS PAPER 1 2024
The VLOOKUP function in Excel
The VLOOKUP function in Excel is used to search for a value in the first column of a table and...
S4 CHEMISTRY
https://acrobat.adobe.com/id/urn:aaid:sc:EU:c0424112-e1de-4038-84a6-6743ec084d39
Range and Nested Loops
Range Function (range())
The range() function is a built-in function in Python used to generate...