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

Understanding Python While Loops

poin

Uploaded by

wavos76886
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)
5 views3 pages

Understanding Python While Loops

poin

Uploaded by

wavos76886
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

While Loop

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.

While Loop Syntax


While expression:
Statement (s)

While Loop Flowchart

While loop falls under the category of indefinite iteration. Indefinite iteration means that
the number of times the loop is executed isn’t specified explicitly in advance.
Statements represent all the statements indented by the same number of character spaces after
a programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements. When a while loop is executed, expr is first
evaluated in a Boolean context and if it is true, the loop body is executed. Then the expr is
checked again, if it is still true then the body is executed again and this continues until the
expression becomes false.
Infinite while Loop in Python
Here, the value of the condition is always True. Therefore, the body of the loop is run infinite
times until the memory is full.

Control Statements
Loop control statements change execution from their normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed. Python
supports the following control statements.

Sentinel Controlled Statement


In this, we don’t use any counter variable because we don’t know how many times the loop
will execute. Here user decides how many times he wants to execute the loop. For this, we
use a sentinel value. A sentinel value is a value that is used to terminate a loop whenever a
user enters it, generally, the sentinel value is -1.
Python while loop with user input
Here, It first asks the user to input a number. if the user enters -1 then the loop will not
execute, i.e.
• The user enters 6 and the body of the loop executes and again asks for input
• Here user can input many times until he enters -1 to stop the loop
• User can decide how many times he wants to enter input

Python while loop with a Boolean Values & break statement


One common use of boolean values in while loops are to create an infinite loop that can only
be exited based on some condition within the loop.
a counter is initialized and then use an infinite while loop (True is always true) to increment
the counter and print its value. Then check if the counter has reached a certain value and if so,
exit the loop using the break statement.
Lab Tasks
1. Write a program to print first 10 integers and their squares using while loop.
2. Write a program to print sum of first 10 Even numbers.
3. Write a program to print table of a number entered from the user.
4. Write a program to show the results mentioned below, in this program values are
provided by the users and stops when the user wants. At the end it should display
(1) Sum
(2) Average
(3) the count of Positive
(4) negative numbers entered
(5) Largest and Smallest Value

Common questions

Powered by AI

Python uses indentation to define blocks of code, and this is significant for while loops as all statements indented at the same level after the loop definition are considered part of the loop body. Proper indentation ensures correct execution flow and avoids syntax errors. Misplaced indents can lead to incorrect loop termination or skipped executions, affecting the program's logic .

The main purpose of using a while loop in Python is to repeatedly execute a block of statements as long as a given condition is true. Unlike definite iteration loops such as for loops, which execute a predefined number of times, while loops fall under the category of indefinite iteration where the number of iterations is not explicitly specified in advance. The loop continues until its condition becomes false .

The benefits of using a sentinel value like -1 in while loops include simplifying the loop termination process in scenarios where a predefined number of iterations is unknown, allowing flexible input-driven execution. However, potential drawbacks are its reliance on the user knowing the sentinel value to stop the loop, which could lead to infinite loops or logical errors if not handled properly .

Loop control statements in Python such as break, continue, and pass, are used to change the execution flow within a loop. The `break` statement exits the loop entirely, `continue` skips the current iteration and proceeds to the next, and `pass` does nothing, serving as a placeholder. An example of using a `break` statement is in a user input loop that exits when a predefined negative number, like -1, is entered, signifying the end of input collection .

A sentinel-controlled loop in Python is implemented using a while loop without a counter variable, as the number of loop executions is determined by user input. Typically, such a loop continues until a sentinel value, often -1, is entered by the user, which signals the termination of the loop. This pattern is useful in situations where the number of iterations cannot be preset and is dependent on user decisions during runtime .

Prefer a while loop over a for loop in scenarios where the number of iterations is not known beforehand and depends on dynamic conditions, such as user input or certain threshold values. This makes while loops suitable for indefinite iteration where conditions guide loop execution until they become false, unlike for loops which are optimal when the number of iterations is predetermined .

To calculate the sum of the first 10 even numbers using a while loop in Python, initialize a sum variable to 0 and a counter to 2. Use a while loop to increment the counter by 2 until 20, adding each counter value to the sum. The resulting sum is 110 .

To use a while loop to print the multiplication table of a user-given number, first take the number as input. Initialize a counter variable at 1. Use a while loop to multiply the input number by the counter and print the result. Increment the counter until it reaches 10. Example: ```python number = int(input('Enter a number: ')) count = 1 while count <= 10: print(f'{number} x {count} = {number * count}') count += 1 ``` This prints the multiplication table from 1 to 10 for the entered number .

A Python while loop can collect user inputs until they enter a sentinel value like -1 to stop. Initialize an empty list and, within the loop, prompt for input and append it unless it matches the sentinel value. The program should output the sum, average, count of positive and negative numbers, and the largest and smallest values entered. After exiting the loop, calculate and display these results based on the collected data .

Infinite loops in Python are constructed using a while loop with a condition that is always True, such as `while True:`. The loop runs indefinitely unless interrupted by an external signal or an internal break statement. To safely terminate an infinite loop, conditions can be added within the loop body to check for specific criteria. For example, a break statement can be used to exit the loop when a counter reaches a certain value .

You might also like