|
1 | | - |
2 | 1 | """ |
3 | | -Check if a number is a prime number. |
| 2 | +This script demonstrates basic operations like greeting a user, |
| 3 | +checking prime numbers, generating primes up to a limit, and |
| 4 | +calculating factorials. |
4 | 5 | """ |
| 6 | +def greet(name): |
| 7 | + """Greets a user with a message.""" |
| 8 | + return f"Hello, {name}!" |
| 9 | + |
5 | 10 | def is_prime(num): |
| 11 | + """Checks if a number is prime.""" |
6 | 12 | if num <= 1: |
7 | 13 | return False |
8 | | - for i in range(2, int(num ** 0.5) + 1): |
| 14 | + for i in range(2, num): |
9 | 15 | if num % i == 0: |
10 | 16 | return False |
11 | 17 | return True |
12 | 18 |
|
13 | | -def count_primes(numbers): |
14 | | - """ |
15 | | - Count the number of prime numbers in a list. |
16 | | - """ |
17 | | - prime_count = 0 |
18 | | - for number in numbers: |
19 | | - if is_prime(number): |
20 | | - prime_count += 1 |
21 | | - return prime_count |
| 19 | +def prime_numbers_up_to(limit): |
| 20 | + """Generates all prime numbers up to a specified limit.""" |
| 21 | + primes = [] |
| 22 | + for num in range(2, limit + 1): |
| 23 | + if is_prime(num): |
| 24 | + primes.append(num) |
| 25 | + return primes |
22 | 26 |
|
23 | | -def main(): |
24 | | - """ |
25 | | - Main function to demonstrate prime number checking. |
26 | | - """ |
27 | | - numbers = [2, 3, 4, 5, 10, 15, 17, 19, 20, 23, 29] |
28 | | - primes = [num for num in numbers if is_prime(num)] |
29 | | - prime_count = count_primes(numbers) |
| 27 | +def factorial(n): |
| 28 | + """Calculates the factorial of a number.""" |
| 29 | + if n in (0, 1): |
| 30 | + return 1 |
| 31 | + result = 1 |
| 32 | + for i in range(2, n + 1): |
| 33 | + result *= i |
| 34 | + return result |
30 | 35 |
|
31 | | - print(f"Numbers: {numbers}") |
32 | | - print(f"Prime numbers: {primes}") |
33 | | - print(f"Total prime count: {prime_count}") |
| 36 | +def main(): |
| 37 | + """Main function to run various operations.""" |
| 38 | + print(greet("Alice")) |
| 39 | + print("\nPrime numbers up to 50:") |
| 40 | + primes = prime_numbers_up_to(50) |
| 41 | + print(primes) |
| 42 | + print("\nFactorial of 5:") |
| 43 | + fact = factorial(5) |
| 44 | + print(fact) |
| 45 | + print("\nPrime numbers up to 100:") |
| 46 | + primes_up_to_100 = prime_numbers_up_to(100) |
| 47 | + print(primes_up_to_100) |
| 48 | + print("\nFactorial of 10:") |
| 49 | + fact_10 = factorial(10) |
| 50 | + print(fact_10) |
34 | 51 |
|
35 | 52 | if __name__ == "__main__": |
36 | 53 | main() |
0 commit comments