Python Prime Number for-else range












0














lower = int(input("from:"))
upper = int(input("to:"))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)


Why does this code print "2" as a prime number? (it is but it should not print it)



2%2==0 so it should skip it...










share|improve this question
























  • What happens when i is 3?
    – Woody1193
    Nov 20 at 19:25








  • 1




    for i in range(2,num) if num is 2 that's empy list so you wont get 2%2==0
    – Filip Młynarski
    Nov 20 at 19:31






  • 1




    Well.... two is a prime number. It can only be divided by itself and one. However, I do see the error in your code causing the unexpected response: range(start,end) needs the end to be greater than the start. Python's duck-typing means a check won't be performed and your if statment doesn't get checked. I wish python didn't do that, but unfortunately it does.
    – Mark_Anderson
    Nov 20 at 19:38


















0














lower = int(input("from:"))
upper = int(input("to:"))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)


Why does this code print "2" as a prime number? (it is but it should not print it)



2%2==0 so it should skip it...










share|improve this question
























  • What happens when i is 3?
    – Woody1193
    Nov 20 at 19:25








  • 1




    for i in range(2,num) if num is 2 that's empy list so you wont get 2%2==0
    – Filip Młynarski
    Nov 20 at 19:31






  • 1




    Well.... two is a prime number. It can only be divided by itself and one. However, I do see the error in your code causing the unexpected response: range(start,end) needs the end to be greater than the start. Python's duck-typing means a check won't be performed and your if statment doesn't get checked. I wish python didn't do that, but unfortunately it does.
    – Mark_Anderson
    Nov 20 at 19:38
















0












0








0







lower = int(input("from:"))
upper = int(input("to:"))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)


Why does this code print "2" as a prime number? (it is but it should not print it)



2%2==0 so it should skip it...










share|improve this question















lower = int(input("from:"))
upper = int(input("to:"))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)


Why does this code print "2" as a prime number? (it is but it should not print it)



2%2==0 so it should skip it...







python python-3.x algorithm primes






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 19:45

























asked Nov 20 at 19:22









Sotiris Liagas

367




367












  • What happens when i is 3?
    – Woody1193
    Nov 20 at 19:25








  • 1




    for i in range(2,num) if num is 2 that's empy list so you wont get 2%2==0
    – Filip Młynarski
    Nov 20 at 19:31






  • 1




    Well.... two is a prime number. It can only be divided by itself and one. However, I do see the error in your code causing the unexpected response: range(start,end) needs the end to be greater than the start. Python's duck-typing means a check won't be performed and your if statment doesn't get checked. I wish python didn't do that, but unfortunately it does.
    – Mark_Anderson
    Nov 20 at 19:38




















  • What happens when i is 3?
    – Woody1193
    Nov 20 at 19:25








  • 1




    for i in range(2,num) if num is 2 that's empy list so you wont get 2%2==0
    – Filip Młynarski
    Nov 20 at 19:31






  • 1




    Well.... two is a prime number. It can only be divided by itself and one. However, I do see the error in your code causing the unexpected response: range(start,end) needs the end to be greater than the start. Python's duck-typing means a check won't be performed and your if statment doesn't get checked. I wish python didn't do that, but unfortunately it does.
    – Mark_Anderson
    Nov 20 at 19:38


















What happens when i is 3?
– Woody1193
Nov 20 at 19:25






What happens when i is 3?
– Woody1193
Nov 20 at 19:25






1




1




for i in range(2,num) if num is 2 that's empy list so you wont get 2%2==0
– Filip Młynarski
Nov 20 at 19:31




for i in range(2,num) if num is 2 that's empy list so you wont get 2%2==0
– Filip Młynarski
Nov 20 at 19:31




1




1




Well.... two is a prime number. It can only be divided by itself and one. However, I do see the error in your code causing the unexpected response: range(start,end) needs the end to be greater than the start. Python's duck-typing means a check won't be performed and your if statment doesn't get checked. I wish python didn't do that, but unfortunately it does.
– Mark_Anderson
Nov 20 at 19:38






Well.... two is a prime number. It can only be divided by itself and one. However, I do see the error in your code causing the unexpected response: range(start,end) needs the end to be greater than the start. Python's duck-typing means a check won't be performed and your if statment doesn't get checked. I wish python didn't do that, but unfortunately it does.
– Mark_Anderson
Nov 20 at 19:38














2 Answers
2






active

oldest

votes


















2














When num is 2, range(2, num) is empty, so the if (num % i) == 0: check is not performed, and the else block executes.






share|improve this answer





























    1














    Others have noted the error in the range(start,end) code. Correcting that, your code for primes could be rewritten as:



    lower = int(input("from:"))
    upper = int(input("to:"))
    for num in range(lower,upper + 1):
    if num > 1:
    for i in range(2,max(num,3)):
    if (num % i) == 0:
    break
    else:
    print(num)


    This isn't the fastest way to get primes mind you, each potential prime must be tested against EVERY smaller number as a possible divisor. It's much faster to instead count upwards and work out the multiples of smaller numbers. That way we only need to do the maths once for each possible divisor.



    For completeness, here is a program that can produce primes efficiently (uses the sieve of Eratosthenes method).



    #### INPUTS    
    lower = int(input("from:"))
    upper = int(input("to:"))

    ### Code
    n = upper
    prime_booleans = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):

    # Is current number a prime, eliminate the numbers that are multiples of it
    if (prime_booleans[p] == True):
    for i in range(p * 2, n+1, p):
    prime_booleans[i] = False
    p += 1

    # Print all prime numbers
    for p in range(lower, n):
    if prime_booleans[p]:
    print p,





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400108%2fpython-prime-number-for-else-range%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      When num is 2, range(2, num) is empty, so the if (num % i) == 0: check is not performed, and the else block executes.






      share|improve this answer


























        2














        When num is 2, range(2, num) is empty, so the if (num % i) == 0: check is not performed, and the else block executes.






        share|improve this answer
























          2












          2








          2






          When num is 2, range(2, num) is empty, so the if (num % i) == 0: check is not performed, and the else block executes.






          share|improve this answer












          When num is 2, range(2, num) is empty, so the if (num % i) == 0: check is not performed, and the else block executes.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 at 19:30









          Patrick Haugh

          26.9k82546




          26.9k82546

























              1














              Others have noted the error in the range(start,end) code. Correcting that, your code for primes could be rewritten as:



              lower = int(input("from:"))
              upper = int(input("to:"))
              for num in range(lower,upper + 1):
              if num > 1:
              for i in range(2,max(num,3)):
              if (num % i) == 0:
              break
              else:
              print(num)


              This isn't the fastest way to get primes mind you, each potential prime must be tested against EVERY smaller number as a possible divisor. It's much faster to instead count upwards and work out the multiples of smaller numbers. That way we only need to do the maths once for each possible divisor.



              For completeness, here is a program that can produce primes efficiently (uses the sieve of Eratosthenes method).



              #### INPUTS    
              lower = int(input("from:"))
              upper = int(input("to:"))

              ### Code
              n = upper
              prime_booleans = [True for i in range(n+1)]
              p = 2
              while (p * p <= n):

              # Is current number a prime, eliminate the numbers that are multiples of it
              if (prime_booleans[p] == True):
              for i in range(p * 2, n+1, p):
              prime_booleans[i] = False
              p += 1

              # Print all prime numbers
              for p in range(lower, n):
              if prime_booleans[p]:
              print p,





              share|improve this answer


























                1














                Others have noted the error in the range(start,end) code. Correcting that, your code for primes could be rewritten as:



                lower = int(input("from:"))
                upper = int(input("to:"))
                for num in range(lower,upper + 1):
                if num > 1:
                for i in range(2,max(num,3)):
                if (num % i) == 0:
                break
                else:
                print(num)


                This isn't the fastest way to get primes mind you, each potential prime must be tested against EVERY smaller number as a possible divisor. It's much faster to instead count upwards and work out the multiples of smaller numbers. That way we only need to do the maths once for each possible divisor.



                For completeness, here is a program that can produce primes efficiently (uses the sieve of Eratosthenes method).



                #### INPUTS    
                lower = int(input("from:"))
                upper = int(input("to:"))

                ### Code
                n = upper
                prime_booleans = [True for i in range(n+1)]
                p = 2
                while (p * p <= n):

                # Is current number a prime, eliminate the numbers that are multiples of it
                if (prime_booleans[p] == True):
                for i in range(p * 2, n+1, p):
                prime_booleans[i] = False
                p += 1

                # Print all prime numbers
                for p in range(lower, n):
                if prime_booleans[p]:
                print p,





                share|improve this answer
























                  1












                  1








                  1






                  Others have noted the error in the range(start,end) code. Correcting that, your code for primes could be rewritten as:



                  lower = int(input("from:"))
                  upper = int(input("to:"))
                  for num in range(lower,upper + 1):
                  if num > 1:
                  for i in range(2,max(num,3)):
                  if (num % i) == 0:
                  break
                  else:
                  print(num)


                  This isn't the fastest way to get primes mind you, each potential prime must be tested against EVERY smaller number as a possible divisor. It's much faster to instead count upwards and work out the multiples of smaller numbers. That way we only need to do the maths once for each possible divisor.



                  For completeness, here is a program that can produce primes efficiently (uses the sieve of Eratosthenes method).



                  #### INPUTS    
                  lower = int(input("from:"))
                  upper = int(input("to:"))

                  ### Code
                  n = upper
                  prime_booleans = [True for i in range(n+1)]
                  p = 2
                  while (p * p <= n):

                  # Is current number a prime, eliminate the numbers that are multiples of it
                  if (prime_booleans[p] == True):
                  for i in range(p * 2, n+1, p):
                  prime_booleans[i] = False
                  p += 1

                  # Print all prime numbers
                  for p in range(lower, n):
                  if prime_booleans[p]:
                  print p,





                  share|improve this answer












                  Others have noted the error in the range(start,end) code. Correcting that, your code for primes could be rewritten as:



                  lower = int(input("from:"))
                  upper = int(input("to:"))
                  for num in range(lower,upper + 1):
                  if num > 1:
                  for i in range(2,max(num,3)):
                  if (num % i) == 0:
                  break
                  else:
                  print(num)


                  This isn't the fastest way to get primes mind you, each potential prime must be tested against EVERY smaller number as a possible divisor. It's much faster to instead count upwards and work out the multiples of smaller numbers. That way we only need to do the maths once for each possible divisor.



                  For completeness, here is a program that can produce primes efficiently (uses the sieve of Eratosthenes method).



                  #### INPUTS    
                  lower = int(input("from:"))
                  upper = int(input("to:"))

                  ### Code
                  n = upper
                  prime_booleans = [True for i in range(n+1)]
                  p = 2
                  while (p * p <= n):

                  # Is current number a prime, eliminate the numbers that are multiples of it
                  if (prime_booleans[p] == True):
                  for i in range(p * 2, n+1, p):
                  prime_booleans[i] = False
                  p += 1

                  # Print all prime numbers
                  for p in range(lower, n):
                  if prime_booleans[p]:
                  print p,






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 20 at 20:03









                  Mark_Anderson

                  421215




                  421215






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400108%2fpython-prime-number-for-else-range%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      Refactoring coordinates for Minecraft Pi buildings written in Python