103k views
2 votes
Write the following code in python 3

A prime number is a number that is only evenly divisible by itself and 1.
Write a boolean function named is_prime which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Use the function in a program that prompts the user to enter the number then displays a message indicating whether the number is prime.

1 Answer

2 votes
def is_prime(n: int) -> bool:
if n in (2, 3):
return True
if n == 1 or n % 2 == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True

# Test the function
print(is_prime(1)) # False
print(is_prime(2)) # True
print(is_prime(3)) # True
print(is_prime(4)) # False
print(is_prime(5)) # True

# Prompt the user to enter a number
num = int(input("Enter a number: "))

# Display a message indicating whether the number is prime
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
User Maki
by
8.2k points