Uploaded by Sanjay S

FALLSEM2022-23 BCSE101E ELA VL2022230105893 Reference Material I 06-10-2022 Class 7 - Loops

advertisement
while loop statement
• Loops in a programming language are used to repeat set of statements
based on a condition. We have two loop statements in python, one is
while statement and the other is for statement.
• A while loop statement in Python repeatedly executes set of
statements as long as the given test expression(condition) is true. When
the condition becomes false, program control passes to the line
immediately following the loop.
• Python while statement syntax is
while test expression:
statement(s) (with indentation)
while Statement Flow Chart
Sample Program 1
• Write a program to display first n numbers based on the user input.
Display the numbers in the same line.
Ex : Input : n = 6
Output : 1 2 3 4 5 6
n=int(input("Enter a number : "))
a=1
while a<=n:
print(a, end=' ' )
a=a+1
Sample Program 2
• Write a program to display the numbers those are divisible by 2 based
on the user input. Display the numbers in the same line separated by a
comma( , ) .
Ex : Input : n = 20
Output : 0,2,4,6,8,10,12,14,16,18,20
n=int(input("Enter a number : "))
a=0
while a<=n:
if a%2==0:
print(a, end=',' )
a=a+1
Sample Program 3
• Write a program to display first n numbers those are divisible by 2
based on the user input. Display the numbers in the same line
separated by a comma( , ).
Ex : Input : n = 6
Output : 2,4,6,8,10,12
n=int(input("Enter a number : "))
a=1 ; i=1
while i<=n:
if a%2==0:
print(a,end=',' )
i=i+1
a=a+1
Sample Program 4
• Write a program to display SUM of first n numbers based on the user
input.
Ex : Input : n = 5
Output : 15
n=int(input("Enter a number : "))
a=1; sum=0
while a<=n:
sum=sum+a
a=a+1
print("Sum is ", sum)
Sample Program 5
• Write a program to display either EVEN or ODD numbers based on the
user input. Display the numbers in the same line.
Ex : Input : n = 10 , Even = Yes/No
Output : 2 4 6 8 10
Sample Program 5
n=int(input("Enter a number : "))
d=int(input("Enter 0 for EVEN, 1 for ODD : "))
a=0
while a<=n:
if d==0:
n=int(input("Enter a number : "))
if a%2==0:
d=int(input("Enter 0 for EVEN, 1 for ODD : "))
print(a, end=' ')
a=0
a=a+1
while a<=n:
else:
if a%2==d:
if a%2==1:
print(a, end=' ')
print(a, end=' ')
a=a+1
a=a+1
Sample Program 6
• Write a program to find factorial of a number based on the user input.
Ex : Input : n = 5
Output : Factorial of 5 is 120
n=int(input("Enter a number to find it's factorial : "))
a=n
fact=1
while n>=1:
fact=fact*n
n=n-1
print("Factorial of", a, " is", fact)
Sample Program 7
• Write a program to display the staircase model based on the number of
rows entered by the user.
Ex : Input : n = 5
Output :
*
**
***
****
n=int(input("Enter no. of rows : "))
* * * * * i=1
while i<=n:
print("* "*i)
i=i+1
Download