So far, I have only used while loops to determine if a number is prime or not. For today, I am going to explain to you how you can use for loop to tell if a number is prime or not.
To understand the code below, you first need to understand what a for loop is. So, what exactly is a for loop? A for loop is a control flow statement for specifying iteration, or repetition, in computer science, which allows code to be performed repeatedly.
So, this is how I did it:
x = 9
is_prime = True
the_primes = [2, 3, 5, 7, 11, 13]
for number in the_primes:
if x % number == 0:
is_prime = False
break
if is_prime == True:
print(f"{x} is a prime number!")
else:
print(f"{x} isn't a prime number.")
Input: x = 9
Output: 9 isn’t a prime number.
As you can see, the way with for loops(above) was very similar to the way with while loops. For loops are regularly used when you have a block of code that you want to repeat a number of times.