0% found this document useful (0 votes)
7 views19 pages

Python Loops: While and For Explained

The document provides an introduction to loops in Python, detailing the two main types: while loops and for loops. It explains their syntax, usage, and includes various examples and challenges for practical understanding, such as printing multiplication tables, counting digits, and checking for palindromes. Additionally, it covers concepts like infinite loops, break, continue, and pass statements, along with the else suite in loops.

Uploaded by

hellowworld994
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)
7 views19 pages

Python Loops: While and For Explained

The document provides an introduction to loops in Python, detailing the two main types: while loops and for loops. It explains their syntax, usage, and includes various examples and challenges for practical understanding, such as printing multiplication tables, counting digits, and checking for palindromes. Additionally, it covers concepts like infinite loops, break, continue, and pass statements, along with the else suite in loops.

Uploaded by

hellowworld994
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

Introduction to Loop’s

▪ Loops are also called as repeating statements.


The loops are of 2 types in python
I. while loop
II. for loop
• If you want a set of statements to repeat again and again in the program
then we use loops. The statements can repeat either ‘for number of times’
or ‘As long as the condition is true’.
• In while condition, If the condition is true, the while block will get
executed after the execution it will go back again and check the condition,
if again the condition is true, it’ll get executed, once the condition
becomes false it'll stop the execution.

Syntax: while condition :


Statements
• Whatever condition you are using in while you should modify it in the
statements else your loop will not work properly.
Example 1: (Statements repeating number of times)
Q) Print hello 10 times using while loop.
#in while loop use the counter as condition and set its value from 1 -10,
modify the counter in the statements and get the result.

count = 0
while count < 10:
print(count + 1, 'Hello')
count = count + 1

Example 2: (As long as the condition is true)


Q) Write a program to print output of the given number from last to first.
# Take input from users in integer form, the condition should be a number
greater than zero and divide the number and print its result in integer form only.

n=int(input("Enter the number: "))


while n>0:
r=n%10
n=n//10
print(r)
While Loop: Student Challenge #
1 Q) Display multiplication table for a given number.
#We have a number and for that we have to print a multiplication table, as the
pattern for multiplying is same, we are using while loop here.

n = int(input('Enter a number for Multiplication Table'))


counter = 1
while counter <= 10:
print(n, 'X', counter, '=', n*counter)
counter = counter + 1
2 Q) Counting the number of digits in a number.
#Taking input from user in integrant write a counter condition in while loop for
just counting the numbers given as input from user.

n = int(input('Enter a Number '))


counter = 0
while n > 0:
n = n // 10
counter += 1
print('Number of Digits are', counter)
3 Q) Finding sum of digits in a number
#If the number is given then find its sum by using while loop

n = int(input('Enter a Number '))


sum = 0
while n > 0:
r = n % 10
n = n // 10
sum = sum + r
print('Sum of Digits is', sum)
4 Q) Reversing a number
#Take input from user and make that given number into reverse order using
while loop

n = int(input('Enter a Number'))
rev = 0
while n > 0:
r = n % 10
n = n // 10
rev = rev * 10 + r
print('Reverse number is', rev)
print(n)
5 Q) Check if a number is a palindrome.
# If the reverse of a number is equal to the original number then we say its a
palindrome
n = int(input('Enter a Number'))
m=n
rev = 0
while n > 0:
r = n % 10
n = n // 10
rev = rev * 10 + r
if m == rev:
print('Number is a Palindrome')
else:
print('Number is not a Palindrome')
6 Q) find sum of given numbers as input
#you have to ask number of numbers by taking user input and find the sum of
that inputs. And we have to count so we use counter for it.
num_of_nos = int(input('Enter number of number'))
sum = 0
count = 0
while count < num_of_nos:
n = int(input('Enter a number'))
sum=sum + n
count = count + 1
print('Sum is ', sum)
7 Q) Find the sum of +ve and -ve number
# user may enter positive or negative number.
num_of_nos = int(input('Enter number of number'))
Psum = 0
Nsum = 0
count = 0
while count < num_of_nos:
n = int(input('Enter a number'))
if n > 0:
Psum = Psum + n
else:
Nsum = Nsum + n
count = count + 1
print('Positive Sum is ', Psum)
print('Negative Sum is ', Nsum)
8 Q) find the maximum numbers from the given number.

num_of_nos = int(input('Enter number of number'))


count = 0
max = int(input('Enter a num'))
while count < num_of_nos - 1:
n = int(input('Enter a number'))
if n > max:
max = n
count = count + 1
print('Max number is', max)
9 Q) Convert decimal to binary.
n = int(input('Enter a number'))
bin = 0
while n > 0:
r=n%2
n = n // 2
bin = bin * 10 + r
brev = 0
while bin > 0:
r = bin % 10
bin = bin //10
brev = brev *10 +r
Solution:
n = int(input('Enter a number'))
bin = ''
while n > 0:
r=n%2
n = n // 2
bin = str(r)+bin
print(bin)
10 Q) Factorial of a number
n = int(input('Enter a number: '))
m=n
fact = 1
if n<0:
print("Negative number factrorial can,t possible. ")
else:
while n>=1:
fact=fact*n
n=n-1
print(m,"factrorial is",fact)
Infinite Loop - break - continue – pass
• Infinite loop is a loop that goes on, which never stops such type of loop is called
infinite loop.
• The following example is of infinite loop.
//This while loop never stops, you need to keep on giving input and it generated
results it never stops

while True:
no = int(input("Enter a number: "))
if no > 0:
print("Positive Number ")
else:
print("Negative Number")

Break Statement
➢ To stop such infinite loop, we can use break statement.
➢ A break statement will stop the loop.
➢ A break statement can be used in other loop situations as well apart from
infinite loop
➢ The below example shows the use of break statement

while True:
no = int(input("Enter a number: "))
if no > 0:
print("Positive Number ")
elif no < 0:
print("Negative Number")
else:
break

Continue Statement
➢ Continue means it will not execute the rest of the loop it will simply go to
beginning of the loop and continue its execution.
➢ Continue is used for logical design.
➢ Let’s understand this with an example
count = 0
while count < 3:
no = int(input("Enter a number: "))
if no % 3 == 0:
continue
print(no)
count = count+1
Pass Statement
➢ Pass - In some cases when you don’t have to do anything use them just
pass the it.
➢ Pass means nothing to do.
➢ In python when you write a block of code you must write something if
there’s nothing to write, then simply write pass statement.
➢ Let’s understand this with an example

while count < 3:


no = int(input("Enter a number: "))
if no % 3 == 0:
pass
else:
print(no)
count = count+1

Else suite
if condition:
---------
----------- {If condition is true then this if}
----------
else:
-----
----- {if condition is false then this else block}
----
-----
----
-----
-----
True-> if block is executed
False->else block is executed

What is else suite?


• The else suite will be always executed irrespective of the statements
in the loop are executed or not.

• If block can be written with while as well as it can also be written with
for loop and also along with try block.
How else suite is useful with while?
Sample:

while condition:
--------- as long as this condition is true
--------- its get executed repeatedly
---------
---------
And once the condition becomes false it will come out of the loop and
executes next statement.

We can also write else block.


while condition:
------------
------------true
------------
else:
--------
-------- false
-------
• If false it will come to else block.
• Suppose if this loop is stopped using break statement without
becoming false. Then this else block will not be executed.
• This else block will execute if only condition becomes false.
• So, it is like if else statement means true if while is executed and if it
is false else will be executed.
• if while never becomes false then else block will never be [Link],
this else block can be used to confirm that while loop has successfully
executed without any break.
Working of else suite
count = 1
while count <= 10:
print(count)
count = count+1
else:
print("Printed all 10 Number ")
print("End of a Program ")
• It has printed all the 10 numbers and also shows that it jumped to else on
becoming false
• Now we will use break to stop the loop

count = 1
while count <= 10:
print(count)
count = count+1
if count > 5:
break
else:
print("Printed all 10 Number ")
print("End of a Program ")

• So, else block is used to confirm that while loop has executed successfully.
And it stops when it becomes false.
• If it stops abruptly using break then else will not execute.

11 Q) GCD and LCM of two number

m = int(input("Enter the first number: "))


n = int(input("Enter the second number: "))
a=m
b=n
while m != n:
if m > n:
m = m-n
else:
n = n-m
print(a, "and", b, "GCD is ", m)
lcm = a*b // m
print(a, "and", b, "LCM is ", lcm)
Introduction: For Loop
• Loops are useful for repeatedly executable statements.

How for loop works


Msg = ‘Hello’

Variable string

Msg Array

H e l l o

So, the string is arranged in the form of an array.

Suppose if we write
for x in msg:
print(x)
It will print like this
H
e
l
l
o
first it prints H

Then again it repeats using for and prints the next letter

H e



X

H e

 

l
✓ It goes on repeating till the end of an array
This loop is also called as for each loop in languages like java and c++
Msg=’hello’
For x in msg: #for loop runs for each statement in the sequence

(print x)
Flow Chart (for loop)

True

For I in
Body of for
range(0,1

false

▪ So, if the value condition is true so loop of the body is executed


continuously and then at one point it stops.
▪ Basically, for loop depends upon the elements in a sequence.
▪ Elements has finished means false and elements has not finished means
true.
What is Range?

• Range is a function
• Suppose range (10)
• 0,1,2,3,4,5,6,7,8,9 it will stop at just one number beforethe last number.
• If you give range (5,10) 5,6,7,8,9

Start End
• Can also give step range (1,10,2) 1,3,5,7,9

Start End Step


• Range (10, 0, -1) 10,9,8,7,6,5,4,3,2,1

Start End Step


• Range (-10, -1, 2) –10, -8, -6, -5, -4,-2

Start End Step


• this is how range function works
Coding
Input:
msg='Hello'
for x in msg:
print(x)

It’s printing as H e l l o one by one. So, for loop executes for each element
inside given statement.
Usually, these types of things which are having elements called as
sequence.
Input:
for i in range(10): #it will take in from 0 to 10
print(i)

for i in range(5,10): #it will print 5 to


10print(i)

for i in range(0,10,2): #it will print on


everytwo steps from 0 to 10
print(i)

for i in range(10,0,-1): #it prints the numbers


inreverse order
print(i)

How i is working?

for i in range (0,10):


print(i)

0 1 2
It works upto 10.
For each i in this range(0,10)
print(i) will be executed Each i is
0,1,2---upto 9

For Loop: Student Challenge #


1 Q) Display multiplication table for a given number.

no = int(input('Enter a Number '))


for i in range(1, 11):
print(no,'X', i,'=',i*no)
2 Q) Find the factorial of a given number.

no = int(input('Enter a Number '))


fact = 1
if no < 0:
print("Negative number factorial is not possible.")
else:
for i in range(1, no+1):
fact = fact * i
print('Factorial of',no,'is', fact)
3 Q) Print n terms of AP series.

a = int(input("Enter initial term: "))


d = int(input("Enter common Difference "))
n = int(input("Enter Number of Terms "))
for t in range(a, a + n * d, d):
print(t)
4 Q) Print n terms of Fibonacci series.

n = int(input('Enter Number of Terms '))


a=0
b=1
print(n," terms Fibonacci series are: ")
for i in range(n):
print(a)
c=a+b
a=b
b=c
5 Q) Find the Factors of a number.

n = int(input('Enter a Number '))


for i in range(1, n+1):
if n % i == 0:
print(i)

6 Q) Check if a number is prime or not.

n = int(input('Enter a Number '))


count = 0
for i in range(1, n+1):
if n % i == 0:
count += 1
if count == 2:
print(n,'is a Prime')
else:
print(n,'is Not a Prime')

7 Q) Break_Continue_Pass with for loop

Break example with for loop:


for i in range(0,10):
if i > 5:
break
else:
print(i)

else suit example with for loop

for i in range(0,10):
print(i)
else:
print("For completed properly")
or
for i in range(0,10):
if i > 5:
break
else:
print(i)
else:
print("For completed properly")
Continue example with for loop:
for i in range(0,10):
if i % 5==0:
continue
print(i)

Pass example with for loop:


for i in range(0,10):
pass
print("Program ended")

Nested Loops

We know that how for loops works


• For example,
for i in range( 0,5):
print ( i )
Output:
0
1
2
3
4
• Loop inside loop is said as nested loop
for i in range( 0,5) :
for j in range( 0,5) :
print ( i , j )
▪ The outer loop can contain any amount of inner loop.
▪ In each iteration of the outer loop inner loop execute all its iteration. For
each iteration of an outer loop the inner loop re-start and completes its
execution before the outer loop can continue to its next iteration.
▪ Working of nested loop

for i in range( 0,5) :


for j in range( 0,5) :
print ( '(',i , j,')', end= " " )
print("")
Q 1) To Print prime numbers 1-100.
for n in range( 1, 100+1):
count=0
for i in range(1, n+1):
if n % i ==0:
count+=1
if count == 2:
print(n)
Q 2) Draw Patterns

*****
*****
*****
*****
*****

for i in range( 0,5):


for j in range(0,5):
print('* ',end=' ')
print('')
or
for i in range(0,5):
print('* '*5)

*
**
***
****
*****
for i in range( 0,5):
for j in range(0,5):
if i>=j:
print('* ',end=' ')
print('')
or
for i in range(0,5):
print('* '* (i+1))
*****
****
***
**
*

for i in range(5,0,-1):
print('* '* i)

Match Case
• Match case is used instead of switch case in languages like c++, java we use
switch case it is like if else.
• It is similar to if else but syntax written is similar to switch case . But works
same as if and elif.
• Example:
day = int(input('Enter Day Number'))
match day:
case 1:
print('Sunday')
case 2:
print('Monday')
case 3:
print('Tuesday')
case 4:
print('Wednesday')
case 5:
print('Thursday')
case 6:
print('Friday')
case 7:
print('Saturday')
case _:
print('Invalid Day Number')
Python range () function:
The Python range () function returns a sequence of numbers, in a given range.
The most common use of it is to iterate sequences on a sequence of numbers using
Python loops.
Python xrange () function:
The xrange () function in Python is used to generate a sequence of numbers,
similar to the Python range () function. The Python xrange () is used only in
Python 2.x whereas the range () function in Python is used in Python 3.x.
Difference between range() and xrange() in Python:

range() xrange()
Returns a list of integers. Returns a generator object.
Execution speed is slower Execution speed is faster.
Takes more memory as it keeps the Takes less memory as it keeps only
entire list of elements in memory. one element at a time in memory.
All arithmetic operations can be Such operations cannot be performed
performed as it returns a list. on xrange().
In python 3, xrange() is not supported. In python 2, xrange() is used to iterate
in for loops.

You might also like