AWS Builder Center
Python Challenge: Finding Prime Numbers and Saving to a File

Python Challenge: Finding Prime Numbers and Saving to a File

A quick walkthrough of a classic programming challenge: using Python to find primes and write them to a text file.

Full-Stack Developer | AWS re/Start Trainee | Building in Public
In our AWS re/Start program, we recently tackled a Python Challenge Lab. The task was simple but practical: write a script that finds all prime numbers between 1 and 250 and saves the results to a text file.
Here is a quick breakdown of how I solved it and what I learned.

The Logic: Finding Primes

A prime number is a number greater than 1 that can only be divided by 1 and itself. To check if a number is prime, you only need to test divisors up to the square root of that number. If none of those divide evenly, the number is prime.
Here is the function I wrote:
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

The File Handling: Saving the Results

Once the logic was working, I used Python's built-in  open()  function with the  "w"  mode to create a file called  results.txt . I looped through numbers 1 to 250, checked if they were prime, and wrote them to the file line by line.
with open("results.txt", "w") as file:
for num in range(1, 251):
if is_prime(num):
file.write(str(num) + "\n")

Why This Matters for Cloud

You might be wondering, "What does finding prime numbers have to do with AWS?"
The core skills are exactly what you need for cloud automation. Writing clean functions, handling loops, and interacting with the file system are the building blocks you will use later when you write Python scripts to automate S3 bucket cleanups or query CloudWatch logs.
The challenge was a great reminder that the fundamentals of programming are the foundation of everything we build in the cloud.
 #python   #aws-restart   #coding-challenge   #file-handling 
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article