English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Example of checking if an integer is a prime number using for loop and if ... else statement. If the number is not a prime, it explains why it is not a prime in the output.
To understand this example, you should understand the followingPython programmingTopic:
greater than1is a positive integer, except1and there are no other factors outside, and the number itself is called a prime.2,3,5,7are prime numbers because they have no other factors.6is not a prime (it is composite), because2 x 3 = 6.
# Program checks if a number is a prime num = 407 # Get input from the user #num = int(input("Enter a number: ")) # Prime numbers are greater than1 if num > 1: # Check characters for i in range(2,num): if (num % i) == 0: print(num, "is not a prime") print(i, "multiplied by", num//(i, "equals", num) break else: print(num, "is a prime") # If the input number is less than # or equal to1It is not a prime else: print(num, "is not a prime")
Output results
407 is not a prime 11multiplied by37equals407
In this program, we will check if the variable num is a prime. Less than or equal to1The number is not a prime.1is performed.
We check if num can be divided by2to num-1divisible by any number. If we find a factor within this range, then the number is not a prime. Otherwise, the number is a prime.
We can narrow the range of numbers to find factors.
In the above program, our search range is2to num - 1.
We can use the range [2,num/2], or [2,num ** 0.5]. The next range is based on the fact that composite numbers must have factors less than the square root of the number. Otherwise, the number is a prime.
You can change the value of the variable num in the source code above to check if the number is a prime of other integers.