0% found this document useful (0 votes)
16 views3 pages

Python While and For Loops Explained

Chapter 5 covers Python loops, specifically the while and for loops. The while loop executes statements repeatedly until a condition is false, while the for loop iterates over a sequence. Examples illustrate how to use both loops for tasks like printing messages and generating multiplication tables.

Uploaded by

vidhu.bhis
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views3 pages

Python While and For Loops Explained

Chapter 5 covers Python loops, specifically the while and for loops. The while loop executes statements repeatedly until a condition is false, while the for loop iterates over a sequence. Examples illustrate how to use both loops for tasks like printing messages and generating multiplication tables.

Uploaded by

vidhu.bhis
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 5 Python

Python While Loop: is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately after the loop
in the program is executed.

Syntax of while loop in Python


while expression:
statement(s)
Flowchart of Python While Loop

Example1: In this example, the condition for while will be True as long as the
counter variable (count) is less than 3.

count = 0
while (count < 3):
count = count + 1
print("Hello")
Output
Hello
Hello
Hello

Example2: Printing the table of 2


num=2
i=1
while i<=10:
print(num, ‘x’, i, ‘=’, num*i)
i=i+1
2x1=2
2x2=4
2x3=6
2x4=8
2x5=10
2x6=12
2x7=14
2x8=16
2x9=18
2x10=20

Python For Loop: The For Loops in Python used for repeated execution of a group of
statements for the desired number of items. For loop is used for iterating over a sequence like
a String, Tuple, List, Set, or Dictionary.

Syntax of For loop in Python


for var in sequence:
# statements

Flowchart of Python For Loop


Example: 1 Python program to display numbers from a list using a for loop.

list = [1,2,4,6,88,125]
for i in list:
print(i)

Output
1
2
4
6
88
125

Example: 2 Python program to print a multiplication table of a given number

given_number = 5
for i in range(11):
print (given_number, " x" , i , " =", 5*i )

Output
5x0=0
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Common questions

Powered by AI

A Python while loop can be used for real-time monitoring by continuously checking a condition without terminating until a stop criterion is met. For example, it can poll for changes in a sensor's data by reading the sensor inside the loop and reacting to specific readings. Python robust libraries, such as time.sleep(), allow for controlled polling intervals to prevent the loop from consuming excessive resources unnecessarily. If the sensor value reaches a certain threshold, the loop can trigger an action or alert. This method ensures that a program consistently checks for updates in real time while being efficient .

While loops in Python are used to execute a block of statements repeatedly as long as a given condition is true, making them useful when the number of iterations is not known beforehand and depends on runtime conditions. For example, a while loop is advantageous for situations where it is necessary to wait for some condition to change during execution, such as user input or server response . For loops, on the other hand, are used for iterating over a sequence of elements such as strings, lists, tuples, sets, or dictionaries. They are ideal when the number of iterations is known or when iterating over collections because they simplify the code and reduce the chance for errors in modifying loop counters .

Python loop constructs can significantly enhance data processing capabilities in real-world analytics scenarios by facilitating batch processing, data filtering, and transformation. For instance, for loops are ideal for iterating over datasets to apply transformations or compute metrics efficiently. By integrating with libraries like Pandas or NumPy, these loops can efficiently handle large datasets, performing operations such as calculations, aggregations, and condition-based filtering. While loops can further aid in implementing adaptive data processing strategies such as iterative approximation methods, enabling dynamic adjustments based on real-time metrics .

A Python for loop can iterate over a dictionary by iterating over its keys, values, or key-value pairs. For example: d = {'a': 1, 'b': 2, 'c': 3} for key, value in d.items(): print(key, value) To modify this loop to search for a specific value, include a condition inside the loop that checks for the value. For instance, if searching for the value '2', the loop would be: for key, value in d.items(): if value == 2: print(f"Key for value 2 is {key}") This would print the key associated with the specific value if found .

To transform the given while loop example into a recursive function, create a function that calls itself with a modified parameter until a base condition is satisfied. For example, the while loop code 'count = 0; while (count < 3): count = count + 1; print("Hello")' can be rewritten as a recursive function like this: def print_hello(count): if count < 3: print("Hello") print_hello(count + 1) print_hello(0). This function increments the 'count' parameter on each call and stops printing once 'count' is no longer less than 3 .

Python does not have a native do-while loop because its philosophy emphasizes simplicity and readability, and do-while loops introduce potential confusion by executing at least once regardless of conditions. However, its functionality can be mimicked by using a while loop where you execute the block statements once before reaching the condition. For instance, execute the block and then place the while condition at the end, creating an initial execution followed by potential repetitions: 'while True: execute_block; if not condition: break'. This structure effectively recreates the do-until behavior .

The examples of 'while' and 'for' loops aid beginner Python programmers in developing several cognitive strategies, such as control flow understanding, algorithmic thinking, and debugging skills. The 'while' loop examples emphasize understanding conditions and runtime logic management, fostering skills in problem decomposition and dynamic decision-making. The examples using 'for' loops, particularly in sequences and multiplication tables, enhance data iteration and sequence handling, further developing precise iteration and computational logic. These skills translate into improved debugging and optimized coding practices .

Using a for loop to print a multiplication table offers greater code simplicity compared to a while loop because a for loop inherently handles the iteration over a range and does not require manual management of the loop counter. For example, 'for i in range(11)' allows you to iterate automatically from 0 to 10, which is more concise than initializing and updating a counter variable required in a while loop, i.e., 'i = 1 while i <= 10'. Both loops have similar execution performance for this task because the operations inside each iteration are identical and depend mainly on the number of iterations rather than the loop structure .

Control flow statements like 'break' and 'continue' allow for more refined control over loop execution. The 'break' statement immediately exits the loop regardless of its remaining iterations, commonly used when a condition for early termination is met. The 'continue' statement, in contrast, skips the rest of the code inside the loop for the current iteration and continues with the next iteration of the loop. For example: for num in range(5): if num == 3: continue print(num) This code will print numbers 0, 1, 2, and 4, skipping the number 3 due to the 'continue' statement .

Nested loops in Python can be used to generate combinations of elements from two different lists by iterating through each element of one list inside the loop of another list. For example: list1 = ['A', 'B'] list2 = [1, 2] for elem1 in list1: for elem2 in list2: print((elem1, elem2)) This code will output: ('A', 1) ('A', 2) ('B', 1) ('B', 2) This approach is useful for exploring all possible pairs of elements between the two lists .

You might also like