[go: up one dir, main page]

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

6 WhileLoop

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 views21 pages

6 WhileLoop

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
You are on page 1/ 21

The While Loop

A while statement executes a block of code repeatedly as


long as the test/ control condition of the loop is true.
The control condition of the while loop is executed before
any statement inside the while loop is executed.
After each iteration, the control condition of the loop is
tested again and the loop continues as long as the
condition remains true.
When the test outcome of this condition becomes false,
the statements in the body of while loop is not executed
and the control is transferred to the statement
immediately following the body of while loop.
Syntax of while loop
while test_expression:
Body of while
Example 2 Output:
Enter a number to find
n = int(input(" Enter a number to find
its factor : 6
its factor : "))
1 2 3 6
print (1) >>>
# one is a factor of every number

factor = 2

while factor <= n/2 :

if n % factor == 0:

print(factor)

factor += 1

print (n)

# every number is a factor of itself


BREAK AND CONTINUE STATEMENTS

Looping constructs allow programmers to repeat tasks


efficiently.

In certain situations, when some particular condition occurs,


we may want the program to exit from a loop (come out of
the loop forever) or skip some statements of the loop before
continuing further in the loop.

These requirements can be achieved by using break and


continue statements respectively.
BREAK STATEMENT
The break statement alters the normal flow of execution as it terminates the current
loop and resumes execution of the statement following that loop.
BREAK STATEMENT

num = 0
for num in range(10):
num = num + 1
if num == 5:
break
print('Num has value ' + str(num))
print('Encountered break!! Out of loop')

Output:
Num has value 1
Num has value 2
Num has value 3
Num has value 4
Encountered break!! Out of loop

When value of num becomes 5, the break statement is executed and the for loop
terminates.
Find the sum of all the positive numbers entered by the user. As soon as the user
enters a negative number, stop taking in any further input from user and display
the sum.
Write a Python program to check if the input number is prime or not.

num = int(input("Enter the number to check :"))


flag = 0 # presume num is a prime number
if num > 1 :
for i in range(2, int(num/2)):
if (num % i == 0):
flag = 1 # num is a not prime number
break # no need to check any further
if flag == 1:
print ( num , "is not a prime number")
else:
print ( num , "is a prime number")
else :
print("Entered number <= 1, execute again!")
Write a Python program to check if the input number is prime or not.
continue statement
When a continue statement is encountered, the control skips execution of
statements inside the body of loop for the current iteration and jumps to the
beginning of the loop for next iteration.

If the loop’s condition is still true, the loop is entered again else the control is
transferred to the statement immediately following the loop.

Like break, continue statement is usually placed in the body of a if statement.


continue statement
continue statement
Example

num = 0
for num in range(6):
num = num + 1
if num == 3:
continue
print('Num has value ' + str(num))
print('End of loop')

Output:
Num has value 1
Num has value 2
Num has value 4
Num has value 5
Num has value 6
End of loop

Observe that the value3 is not printed in the output, but the loop continues after that
point to print other values before exiting the loop.
NESTED LOOPS
A loop may contain another loop inside it. A loop inside another loop is called a nested
loop.

Example
Output:
for b in range(4): Iteration 1 of outer loop
1
print( "Iteration " +str(b+1)+ " of outer loop")
2
for a in range(3): # nested loop 3
print(a+1) Out of inner loop
Iteration 2 of outer loop
print("Out of inner loop")
1
print("Out of outer loop") 2
3
Out of inner loop
Iteration 3 of outer loop
1
2
3
Out of inner loop
Iteration 4 of outer loop
1
2
3
Out of inner loop
Out of outer loop
Python does not impose any restriction on how many loops can be nested inside a loop or
on the levels of nesting. Also, a for loop may be nested inside a while loop, a while loop may
be nested inside a for loop, a while loop may be nested in a while loop or a for loop may be
nested in a for loop as in the above example.

Write a program to print the pattern for a number n input by the user, (here n = 5)
1
12
123
1234
12345

Solution:
num =int(input("Enter number of rows = "))
for i in range(1,num+1):
for j in range(1,i+1):
print(j, end ="")
print()

Output:
Enter number of rows = 5
1
12
123
1234
12345
Write a program to reverse a number input by the user

# Python Program to Reverse a Number using While loop


Number = int(input("Please Enter any Number: "))
Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10
print("\n Reverse of entered number is = “, Reverse)

Output:
1456
6541
Write a program to sum the digits of a number input by the user

# Python Program to find Sum of Digits of a Number using While Loop

Number = int(input("Please Enter any Number: "))


Sum = 0
while(Number > 0):
Reminder = Number % 10
Sum = Sum + Reminder
Number = Number //10
print("\n Sum of the digits of Given Number = %d" %Sum)

Output:
1456
16
For loop with else block

In Python we can have an optional ‘else’ block associated with the loop.
The ‘else’ block executes only when the loop has completed all the iterations.
Lets take an example:

for val in range(5):


print(val)
else:
print("The loop has completed execution")

Output:
0 1 2 3 4 The loop has completed execution

Note: The else block only executes when the loop is finished.
Infinite while loop

Example 1:
This will print the word ‘hello’ indefinitely because the condition will
always be true.

while True:
print("hello")

Example 2:
num = 1
while num<5:
print(num)

This will print ‘1’ indefinitely because inside loop we are not updating
the value of num, so the value of num will always remain 1 and the
condition num < 5 will always return true.
Nested while loop in Python

When a while loop is present inside another while loop then it is called nested
while loop. Lets take an example to understand this concept.

i = 1
j = 5
while i < 4:
while j < 8:
print(i, ",", j)
j = j + 1
i = i + 1

Output:
1 , 5
2 , 6
3 , 7
Python – while loop with else block

We can have a ‘else’ block associated with while loop. The ‘else’ block is
optional. It executes only after the loop finished execution.

num = 10
while num > 6:
print(num)
num = num-1
else:
print("loop is finished")

Output:
10 9 8 7
loop is finished

You might also like