0% found this document useful (0 votes)
276 views4 pages

Python While Loop Syntax and Examples

The while loop in Python repeatedly executes the block of code as long as a given condition is true. It checks if the condition is true before executing the code block. The code block is executed and then the condition is checked again. This continues until the condition becomes false, at which point the code continues execution at the line after the while loop. Python uses indentation to group statements that are part of the while loop code block rather than brackets.

Uploaded by

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

Python While Loop Syntax and Examples

The while loop in Python repeatedly executes the block of code as long as a given condition is true. It checks if the condition is true before executing the code block. The code block is executed and then the condition is checked again. This continues until the condition becomes false, at which point the code continues execution at the line after the while loop. Python uses indentation to group statements that are part of the while loop code block rather than brackets.

Uploaded by

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

while loop statement in Python programming language repeatedly executes a target


statement as long as a given condition is true.

Syntax

The syntax of a while loop in Python programming language is −


while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
In Python, 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.

Example

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

Using else Statement with While Loop


Python supports to have an else statement associated with a loop statement.
 If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise else statement
gets executed.
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
Exercise Question 1: Print First 10 natural numbers using while loop
Solution :
i=1
while i<=10:
print (I,end=” “)
i=i+1

Exercise Question 2: Print the following pattern


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Solution :
i=1
while i<=5:
j=1
while j<=5:
print(j,end=” “)
j =j+1
print()
i=i+1
Exercise Question 3: Accept number from user and calculate the sum of all number between 1 and
given number
Solution :
num=int(input("Enter the number "))
sum=0
i=1
while i<=num:
sum=sum+i
i=i+1
print("The sum of natural number from",1, "to ",num," is ",sum)

Exercise Question 4: Print multiplication table of given number


Solution :
num=int(input("Enter the number "))
i=1
while i<=10:
print(num,"x",i,"=",i*num)
i=i+1

Exercise Question 5: Display Fibonacci series up to 10 terms


A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This
means to say the nth term is the sum of (n-1)th and (n-2)th term
Solution :
USING WHILE LOOP
num=int(input("Enter the limit "))
a=0
b=1
c=0
print(a," ",b,end=" ")
i=1
while i<=num:
c=a+b
print(c,end=" ")
a=b
b=c
i=i+1

USING FOR LOOP


num=int(input("Enter the limit "))
a=0
b=1
c=0
print(a," ",b,end=" ")
for i in range(1,num+1):
c=a+b
print(c,end=" ")
a=b
b=c

Exercise Question 6: Write a loop to find the factorial of any number


The factorial (symbol: !) means to multiply all whole numbers from our chosen number down to 1.
Solution :
num=int(input("Enter the NUMBER "))
i=num
fact=1
while i>=1:
fact=fact*i
i=i-1
print("The factorial of ",num,"is ",fact)
Eg : if num is 5 then = 5 x 4 x 3 x 2 x 1 = 120

Exercise Question 7: Display the cube of the number up to a given integer


Solution :
num=int(input("Enter the NUMBER "))
i=1
while i<=num:
print(i*i*i,end=" ")
i=i+1
Exercise Question 8: Find the sum of the series 2 +22 + 222 + 2222 + .. n terms
Solution :
num=int(input("Enter the limit "))
start = 2
sum = 0
i=1
while i<=num:
print(start, end=" ")
sum += start
start = (start * 10) + 2
i=i+1
print("\nSum of above series is:", sum)

Exercise Question 9: Print the following pattern


*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Solution :
i=1
while i<=5:
j=1
while j<=i:
print("*",end=" ")
j=j+1
print()
i=i+1
i=4
while i>=1:
j=1
while j<=i:
print("*",end=" ")
j=j+1
print()
i=i-1

Common questions

Powered by AI

Designing a loop to calculate cubes up to a specified limit might present challenges such as handling edge cases, efficiently managing calculations for large inputs, and ensuring output format consistency. In Python, addressing these issues includes validating user input to prevent erroneous data, managing loop bounds to avoid unnecessary iterations, and using appropriate print formatting to guarantee coherent output. Proper input handling and systematic increments within the loop help accommodate extended sequences while ensuring the program remains efficient and readable .

To calculate the factorial of a number using a while loop in Python, initialize a variable 'fact' to 1 and another variable 'i' to the given number. Use a while loop that continues while 'i' is greater than or equal to 1, multiplying 'fact' by 'i' in each iteration and decrementing 'i'. This approach is effective because it conceptually mirrors the mathematical process of calculating a factorial, multiplying each sequential integer downward toward 1. It ensures clarity and correctness, as the loop execution directly represents the factorial definition .

To use a while loop in Python to generate the series 2 + 22 + 222 + up to n terms, initialize variables for the starting number (2 in this case) and a sum accumulator. The loop condition should iterate up to the number of terms (n). Within the loop, add the current number to the sum, then update the current number by appending another 2 at the end (multiply by 10 and add 2). This iterative process allows the loop to construct and sum the series by building each term based on the previous one and summing it in each iteration .

Indentation in Python's while loop is used to group statements that should be executed together within the loop block. Python uses indentation to define the scope of loops, functions, and other constructs, which means that all statements indented by the same level after a programming construct are considered part of the same block. This affects code execution by ensuring that all indented statements are executed as part of the loop until the condition becomes false .

The 'end' parameter in the Python print function is used to specify what should be printed at the end of the output. By default, it adds a newline character. However, modifying it allows for different output formatting, such as printing on the same line or using a specific separator. For instance, in loops, setting 'end' to a space or empty string keeps the output on the same line, which is useful for displaying sequences or patterns without starting a new line for each item .

To display the Fibonacci sequence using a while loop in Python, initialize variables for the first two terms (0 and 1) and a counter. With a while loop, print the current Fibonacci numbers and calculate the next number by summing the two preceding terms. Update the values of the terms to the next pair in the sequence for the subsequent iteration. The loop is suitable for this task because the Fibonacci sequence relies on using previous terms to calculate the next term, and the loop can effectively manage this dependency by maintaining and updating the variable states .

Patterns can be printed using nested while loops in Python by controlling the number of inner loop iterations based on the outer loop counter. Each iteration of the outer loop typically represents a row in the pattern, and the inner loop creates the content within that row. Key considerations include setting precise start and end conditions for both loops to achieve the desired shape and using the 'end' parameter in print statements to manage spacing. Proper indentation and careful manipulation of loop variables ensure the output aligns correctly, as in printing triangle or pyramid shapes .

When an else statement is included with a while loop in Python, the else block is executed when the loop condition becomes false. This means the code within the else block will run after the loop has finished iterating over the given condition. For example, if a while loop is iterating through numbers and the condition checks for numbers less than 5, once a number reaches 5, the loop stops and the else block is executed, printing or performing the final step in the process .

A while loop is generally more advantageous when the number of iterations is not predetermined and depends on a dynamic condition that could change during the execution. It offers more flexibility for complex conditions compared to a for loop, which is best suited for iterating over a fixed range or collection of items. For example, while loops can be used for reading inputs until a certain condition is met, such as processing user input until they indicate termination, or implementing intricate logic that requires additional operations before evaluating the loop's continuation condition .

Handling user input in control statements is crucial for creating flexible and interactive Python programs, allowing variables to adapt to diverse use cases and execute calculations dynamically. This flexibility is essential in scenarios like generating mathematical tables, calculating factorials, or computing summations based on user-provided limits. User input ensures that loops perform computations pertinent to the user's context, enhancing program functionality and usability by enabling a single code structure to serve various input scenarios efficiently .

You might also like