0% found this document useful (0 votes)
5 views

Chapter 8

Chapter 8 discusses loops in Python, specifically the FOR and WHILE loops, which are used for repeating a set of statements based on conditions. It provides multiple examples of how to implement these loops for various tasks, such as printing numbers, calculating sums, and checking for prime numbers. Additionally, the chapter includes exercises and questions to reinforce understanding of loop concepts and their applications.

Uploaded by

Maw Koon Myat
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 views

Chapter 8

Chapter 8 discusses loops in Python, specifically the FOR and WHILE loops, which are used for repeating a set of statements based on conditions. It provides multiple examples of how to implement these loops for various tasks, such as printing numbers, calculating sums, and checking for prime numbers. Additionally, the chapter includes exercises and questions to reinforce understanding of loop concepts and their applications.

Uploaded by

Maw Koon Myat
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/ 12

Chapter 8: More About Python

Loops in Python

Sometimes there may be a need to repeat a set of statements more than once based on a
certain condition. This process of repetition is called a loop or iteration in programming.

For example:
​ FOR ... loop​ ​ ​ WHILE ... loop

FOR loop

The FOR ... structure is used to repeat a loop a specific number of times. It uses a counter
variable which is incremented or decremented with each repetition of the loop.

FOR loop syntax 1:


for counter_ variable in( <collection>):
statement(s)

WHILE loop

A WHILE loop executes a block of code repeatedly as long as the test/control condition of the
loop is true. It is useful when the number of iterations are not known prior to the execution of the
loop.

WHILE loop syntax 1


while <condition>:
statement(s)
.Program 1: Write a program using the FOR loop to print the first ten natural numbers.

for i in range(1, 11):


print(i)

Program 2: Write a program using the FOR loop to print the first ten multiples of 2.

for i in range(2, 21, 2):


print(i)

Program 3: Write a program using the FOR loop to print the first ten natural numbers in reverse
order.

for i in range(10, 0, -1):


print(i)

Program 4: Write a program using the FOR loop to print the multiplication table of a number N.

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


for i in range(1, 11):
print(N, "*", i, "=", N * i)

In the above example, the value of the variable N is accepted from the user. The sample
program is executed for the input value N=5.

Program 5: Write a program using the FOR loop to print X raised to the power of Y.

X = int(input("Enter the value of X: "))


Y = int(input("Enter the value of Y: "))
Power = 1
for Count in range(1, Y + 1):
Power *= X
print(X, "^", Y, "=", Power)
Program 6: Write a program using the FOR loop to accept ten numbers from the user and
display their sum.

Sum = 0
for i in range(1, 11):
N = int(input("Enter a number: "))
Sum += N
print("The sum of 10 numbers is:", Sum)

Program 7: Write a program using the FOR loop to display factors of number N.

N = int(input("N="))
Fact = 1
for Count in range(1, N + 1):
Fact *= Count
print(N, '!=', Fact)

Program 8: Write a program using the FOR loop with strings.

for Counter in "Python":


print(Counter)

Program 9: Write a program using the FOR loop with else to print multiples of 2.

for Count in range(2, 20, 2):


print(Count, end=", ")
print("All done!")

Program 10: Write a program using the WHILE loop to print the first five natural numbers.

Count = 1
while Count <= 5:
print(Count, end=", ")
Count = Count + 1
Program 11: Write a program using the WHILE loop to display the digits of a number in reverse
order.

Num=int(input(“Number”))
​ Count=1
​ While Num>0:
​ R=Num%10
​ print(R)
​ Num//=10​

Program 12: Write a program using the WHILE loop to display the factors of a number.

Num = int(input("Number: "))


Count = 1
while Count <= Num:
if Num % Count == 0:
print(Count, end=", ")
Count = Count + 1

Program 13: Write a program using the WHILE loop to display the Fibonacci series to the Nth
term, i.e. 0,1,1, 2, 3, 5, . .. , N.

Num = int(input("Number: "))


A=0
B=1
Count = 1
while Count <= Num:
print(A, end=", ")
A, B = B, A + B
Count = Count + 1
Program 14: Write a program using the WHILE loop with else to check if a number is a prime
number.

Num = int(input("Number = "))


I=2
while I < Num:
if Num % I == 0:
print(Num, "is not a prime number")
break
I += 1
else:
print(Num, "is a prime number")

Program 15: Write a program to implement the WHILE loop with break.

i=1
while i <= 5:
print(i)
if i == 3:
break
i=i+1
print("The end")

Program 16: Write a program to implement the WHILE loop with continue.

i=1
while i < 5:
i += 1
if i == 3:
continue
print(i)
print("The end")
.Activity

Spot and correct any errors in the following programs.

1.
For x in range(1,11)
Print x
End

Ans:
for x in range(1, 11):
print(x)

2.
Num==1
While
Num<=5)
print(Num*5)
Num+1=Num

Ans:
Num = 1
while Num <= 5:
print(Num * 5)
Num += 1

3.
Num=int("Enter Num=")
for I in range[0,11]
if x=y
print x+y
else
print x-y

Ans:
Num = int(input("Enter Num="))
for i in range(0, 11):
if x == y:
print(x + y)
else:
print(x - y)
.Exercise

A. Fill in the blanks.

1. The continue statement skips the rest of the loop statements and causes the next iteration of
the loop to take place.
2. The break statement enables a program to skip over a part of the code.
3. The else part of the while loop is executed only when the while loop completes all its
iterations.
4. Condition is checked for True or False, and the statements are executed only if the condition
is True.
5. The while loop is helpful when the number of iterations are not known prior to the execution
of the loop.

B. Convert the following loops as directed.

1. while => for


x=5
while x < 10:
print(x + 10)
x += 2

Ans:
for x in range(, 10, 2):
print(x + 10)

2. for = while
for x in range(5, 20, 5):
print(x)

Ans:
x = 5 while x < 20:
print(x)
x += 5
C. Give the output for the following codes.

1.
Num = 0
while (Num < 10):
Num += 1
if Num == 5:
break
print(Num, end=",")

Ans:​ 1,2,3,4,

2.
for val in "String":
if val == "I":
break
print(val)
print("Over")

Ans:
S
t
r
i
n
g
Over
D. Write Python programs for the following.

1. Write a program to accept a number from the user and display if it is a palindrome or
not. [Hint: A palindrome number is where the reverse of the number is the same as the
number itself.]

Input
Num=1221
Num=231

Output
Palindrome Number
Not a Palindrome Number

Ans:
Input
n = int(input("Enter number: "))
temp = n
rev = 0

while n > 0:
dig = n % 10
rev = rev * 10 + dig
n = n // 10

if temp == rev:
print("Palindrome Number")
else:
print("Not a Palindrome Number")

Output (Example) (u don’t need to answer this)


Enter number: 1221
Palindrome Number

Enter number: 231


Not a Palindrome Number
2. Write a program to accept a number and find out whether it is a perfect number or not.
[Hint: A perfect number is a positive integer that is equal to the sum of its proper
divisors. The smallest perfect number is 6.]

Ans:
n = int(input("Enter number: ")) # Fixed quotes
sum = 0

# Loop should run till n (excluding n), not (n-1)


for i in range(1, n):
if n % i == 0: # Fixed incorrect mod operation
sum += i # Fixed indentation

# Check condition should be outside the loop


if sum == n:
print("Perfect number")
else:
print("Not a perfect number")

3. Write a program to accept a number from the user and check if it ends with 4 or 8. If it
ends with 4, print "Ends with 4", if it ends with 8, print "Ends with 8", otherwise print
"Ends with neither".

Ans:
n = int(input("Enter number:"))
mod = n % 10
if mod == 8:
print("ends with 8")
elif mod == 4:
print("ends with 4")
else:
print("ends with neither")

4. Write a program to calculate and print the sum of even and odd integers of the first N
natural numbers.

Ans:
n = int(input("Enter a number: "))
sum1 = 0
while(n > 0):
sum1 = sum1 + n
n=n-1
print("The sum of first n natural numbers is", sum1)
E. Answer the following questions.

1. What is the significance of using iterations in Python?


Ans:​ Sometimes there is a need to repeat a set of statements more than once based on a
certain condition. This process of repetition is called loop or iteration in programming. A loop, is
thus used to repeat a block of statements a specific number of times. The loops used in Python
are for loop and while loop.

2. Explain the range() function with the help of an example.


Ans:​ The range() function is used to create a list containing a sequence of numbers starting
from start and ending with one less than the stop.
Syntax: range([start], stop,[step])
Example: >>>range(10); output: [0,1,2,3,4,5,6,7,8,9]

3. Explain the difference between FOR and WHILE loops.


Ans:​ for… structure is used when you want to perform a loop a specific number of times. It
uses a counter variable which is incremented or decremented with each repetition of the loop. A
while loop executes a block of code repeatedly as long as the test/control condition of the loop
is true. It is ideally suited when the number of iterations are not known prior to the execution of
the loop.
.Lab work

1. Series: 2 + 4 + 6 + ... Nth term


Ans:
def sum_series_1(n):
return sum(2 * i for i in range(1, n + 1))

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


print("Sum of series:", sum_series_1(n))

2. Series: 10 + 20 + 30 + ... Nth term


Ans:
def sum_series_2(n):
return sum(10 * i for i in range(1, n + 1))

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


print("Sum of series:", sum_series_2(n))

3. Series: X + X² + X³ + ... Nth term


Ans:
def sum_series_3(x, n):
return sum(x ** i for i in range(1, n + 1))

x = int(input("Enter the value of X: "))


n = int(input("Enter the number of terms: "))
print("Sum of series:", sum_series_3(x, n))

4. Series: 1! + 2! + 3! + ... Nth term


Ans:
import math

def sum_series_4(n):
return sum(math.factorial(i) for i in range(1, n + 1))

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


print("Sum of series:", sum_series_4(n))

You might also like