I am trying checking the divisibility of 5 and 7 for the numbers in the range from 1 to 41 using a while
loop. I know that there are other options, such as a for
loop, but I would like to understand how the code needs to be set up with a while
loop. This is the code I wrote:
n = 1
m = 41
div = [5,7]
while(n<=m):
if n == 13:
continue
if n%div[0]==0 and n%div[1]==0:
print(n, 'the number is divisible for both 5 and 7')
elif n%div[0]==0:
print(n, 'the number is divisible for 5')
elif n%div[1]==0:
print(n, 'the number is divisible for 7')
else:
print(n, 'is divisible for neither 5 or 7')
On the Jupyter session, it didn't return an error, but it takes a significant amount of time to process the output. Can someone tell me how to properly modify this code?
The continue
would block the while loop to go any further when n == 13
.
Other than that, the code and algorithm are actually correct. You just forgot to set an incremental structure (n+=1)
.
n = 1
m = 41
div = [5,7]
while(n<=m):
if n == 13:
n+=1
if n%div[0]==0 and n%div[1]==0:
print(n, 'the number is divisible for both 5 and 7')
elif n%div[0]==0:
print(n, 'the number is divisible for 5')
elif n%div[1]==0:
print(n, 'the number is divisible for 7')
else:
print(n, 'is divisible for neither 5 or 7')
n+=1