内容中心

2026年评价高的广州产品宣传片制作售后无忧公司-广州改变广告有限公司

Here's a useful Python script that checks if a given number is prime. It includes input validation and handles edge cases (like non-integer inputs, numbers less than 2):

def is_prime(n):
    """Check if a number is a prime number."""
    if n <= 1:
        return False  # Numbers <=1 are not prime
    if n == 2:
        return True   # 2 is the only even prime
    if n % 2 == 0:
        return False  # Even numbers >2 are not prime

    # Check odd divrs from 3 up to sqrt(n)
    for i in range(3, int(n**0.5) + 1, 2):
        if n % i == 0:
            return False
    return True

# Main execution
if __name__ == "__main__":
    try:
        number = int(input("Enter a number to check for primality: "))
        result = is_prime(number)
        print(f"{number} is {'a prime number' if result else 'not a prime number'}.")
    except ValueError:
        print("Error: Please enter a valid integer.")

What this script does:

  1. Prime Check Logic:
    • Rejects numbers ≤1 (not prime).
    • Handles 2 (only even prime).
    • Skips even numbers >2 (since they can't be prime).
    • Checks divisibility by odd numbers up to the square root of the input (efficient, as factors larger than sqrt(n) would have a corresponding factor smaller than sqrt(n)).
  2. Input Validation: Catches non-integer inputs and shows an error message.

You can run this script directly—just enter a number when prompted, and it will tell you if it's prime! If you had a specific task in mind (like file handling, data analysis, or something else), feel free to share more details, and I'll adjust the script accordingly.

广州改变广告有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?