Validating given input and printing every prime number =< given input. (Python)

Question:

So I have read tons of solutions to this type of questions, but they all seem to be way too complicated, or I can’t find any useful solutions in them.

I have written the first part where I have to ask for an input and validate it to be an integer, but I can’t figure out how to write the code for the second part. Efficiency isn’t a necessity here, but I think it’s better if I learn the most efficient way from the get go. From what I read, using the radicle of the input and checking the divisors is the way to go here, but as I said, I can’t figure out how to actually write the code and integrate it into what I already have.

while True:
    x = str(input("Please enter an integer:  "))
    try:
        x = int(x)
    except ValueError:
        print("Please enter a valid integer: ")
        continue
    
    break

Any help is greatly appreciated!

Asked By: Juj

||

Answers:

Write an isPrime(n) function that returns true if n is prime, false otherwise. Then test all the numbers from 2 up to the entered integer to see if they are prime.

We will help you to improve your code, but you have to write it first.

Answered By: rossum

It is better to edit multi-line code into your question, rather than post a comment, because then you are not limited to a single line.

Your code appears to be:

def is_prime2(n):
   if n == 2 or n == 3:
     return True
   #endif
   if n % 2 == 0 or n < 2:
     return False
   #endif
   for i in range(3, int(n**0.5)+1, 2):
     if n % i == 0:
       return False
     #endif
   #endfor
   return True
#enddef
print(n)

I have added comments to indicate where I think that various statements end. I may have mistaken the indentation converting from a single line.

Apart from that print(n), which is either not part of the function definition or comes after a return, this appears to work correctly. It will be too slow for very large values of n though it will be fine for smaller values and for testing. For very large values have a look at the Sieve of Eratosthenes.

Answered By: rossum
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.