Page 261 - CTS - CSA TP - Volume 2
P. 261
COMPUTER SOFTWARE APPLICATION - CITS
TASK 2: While loops in Python for Printing those numbers divisible by either 5 or 7 within 1 to
limit using a while loop
Code:
# Take user input to set the limit for the loop
limit = int(input(“Enter the Limit: “))
# Initialize a variable i with the value 1
i = 1
# The loop will continue as long as i is less than the specified limit
whilei< limit:
# Check if the current value of i is divisible by 5 or 7
ifi % 5 == 0 or i % 7 == 0:
# Print the current value of i, followed by a space instead of a newline
print(i, end=’ ‘)
# Increment the value of i by 1 in each iteration
i+=1
Explanation:
• limit = int(input(“Enter the Limit: “)): Takes user input to set the upper limit for the loop. The int() function is used
to convert the input to an integer.
• i = 1: Initializes a variable i with the value 1.
• whilei< limit:: The while loop continues as long as i is less than the specified limit.
• if i % 5 == 0 or i % 7 == 0:: Checks whether the current value of i is divisible by 5 or 7. The % operator
calculates the remainder after division.
• print(i, end=’ ‘): If the condition in the if statement is true, it prints the current value of i, followed by a space
instead of a newline.
• i += 1: Increments the value of i by 1 in each iteration of the loop.
The loop iterates through the numbers from 1 to the specified limit, and for each number, it checks if it is divisible
by 5 or 7. If the condition is true, it prints the number. The loop continues until i reaches the specified limit.
Output:
TASK 3: Write a program for the sum of squares of the first n natural numbers using a while loop
Code:
# Python program example to show the use of while loop
# Take user input to set the limit for the loop
n = int(input(“Enter the limit: “))
# Initializing summation and a counter for iteration
summation = 0
c = 1
246
CITS : IT & ITES - Computer Software Application - Exercise 126