0

I am a newbie in Python programming and I need a feedback. I wrote a program that prints prime numbers up to the given integer. But the output is different than expected. Could you please give me a feedback about this code. What am I doing wrong and why?

Thank you so much.

user_integer = int(input("Please enter an integer : "))
for num in range(0, user_integer + 1):
    for i in range(2, num):
        if (num % i) == 0:
            break
        else:
            print(num)
shiva
  • 5,083
  • 5
  • 23
  • 42
  • 1
    Welcome :) It's good practice to say what the output was and what you were expecting – 7koFnMiP Oct 29 '20 at 11:29
  • 2
    Does this answer your question? [Prime Numbers python](https://stackoverflow.com/questions/35391063/prime-numbers-python) – Ale Oct 29 '20 at 11:31
  • You should also look at better algorithms, such as [Sieve of Eratosthenes - Finding Primes Python](https://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python) – Booboo Oct 29 '20 at 11:41
  • There is an example code of finding prime numbers in [Python Tutorial](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) – adamkwm Oct 29 '20 at 11:49

3 Answers3

1

This code:

user_integer = int(input("Please enter an integer : "))
for num in range(0, user_integer + 1):
    for i in range(2, num):
        if (num % i) == 0:
            break
        else:
            print(num)

will print every odd number, including non-primes. Let num be equal 9 then 9%2==0 is False and else body is executed. You should firstly check all potential divisors and then print if appriopate that is:

user_integer = int(input("Please enter an integer : "))
for num in range(2, user_integer + 1):
    for i in range(2, num):
        if (num % i) == 0:
            break
    else:
        print(num)

Output (for input 25):

2
3
5
7
11
13
17
19
23

Note identation of else - here it is part of for-else not if-else, so print is done if and only if there was not break issued.

Daweo
  • 31,313
  • 3
  • 12
  • 25
1

Your error is caused by the placement of your else statement.

Essentially, the else statement executes every time the number cannot be divided. So for instance with the number nine:

9 % 2 isn't equal to 0, so it will print 9, even though nine isn't prime.

You could do something like this.

user_integer = int(input("Please enter an integer : "))

for num in range(0, user_integer + 1):
    for i in range(2, num):
        if (num % i) == 0:
            break
        
    else:
        print(num)
hhaefliger
  • 521
  • 3
  • 18
-2

If you are new at python, better start looking at writing optimized codes. you can use list comprehension to achieve like [i for i in range(0,user,integer)]

Don
  • 3,876
  • 10
  • 47
  • 76
Akshay
  • 31
  • 3