Python script that checks if a given number is prime and handles invalid input? #134677
Replies: 3 comments
-
|
Thanks for posting in the GitHub Community, @avagoji and apologies for the delay! I was reviewing our backlog and your discussion was in the wrong category. We’ve moved your post to our Programming Help 🧑💻 category, which is more appropriate for this type of discussion. Please review our guidelines about the Programming Help category for more information. |
Beta Was this translation helpful? Give feedback.
-
|
Here is an example code with comments. If you don't understand any part, let me know. |
Beta Was this translation helpful? Give feedback.
-
|
Here’s a simple script I used when I was learning: def is_prime(n):
if not isinstance(n, int) or n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
try:
num = int(input("Enter a number: "))
print("Prime!" if is_prime(num) else "Not prime.")
except ValueError:
print("Please enter a valid integer.")It checks for invalid input and handles edge cases too. Clean and works well for small numbers. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Select Topic Area
Question
GitHub Feature Area
Actions
Body
How do you create a Python script that checks if a given number is prime and handles invalid input?
Beta Was this translation helpful? Give feedback.
All reactions