2

Im new here, hopefully i can ask question that is okey to ask here, but i've been fighting last hours with Python, im trying to make a program as simple as possible to tell the user if the number they choose to write in is a prime number or not a prime number. Thing is, i managed to make it work, then somehow i did'nt save it so lost it.

My code so far

n = int(input("Enter a number: "))
    
for i in range(2, n):
    if (n%i == 0):
        break
        quit (str(n) + " is not a prime number")
print (n, "is a prime number")

This makes my program tell the user that whatever number that is choosen, it will say "is a prime number" Before i did'nt have the break function there, i added it and changed something else and it worked somehow.

Any idea?...

Im very new to programming, python is my second language. I expect that the program to tell user to enter a number from number 2 to 101 if a number is a prime number it will print in console or a not a prime number and print it.

My idea: The program starts by asking for an integer. Then a for loop starts with a range from the number 2, up to 100. Once inside the loop, do the same check as we did in the Scratch program, that is, check if the number n modulo i = 0 where i starts at two and count up to the number we entered (but not including the number we entered). If we get an answer here that gives 0 in the remainder, then it is not a prime number and this is printed on the screen with the text "is not a prime number" and at the same time ends the program. If no answer is given where we get 0 in the remainder, then it is a prime number and the number together with the text "is a prime number" is instead printed on the screen.

I wish i could just ask a friend, but lets give this forum a shot!

Let me know if this kind of question is not suitable in this forum! Take care Chris

  • The line `quit (str(n) + " is not a prime number")` cannot be reached. The `for` loop exits when `break` is executed. – timgeb Dec 12 '22 at 14:28
  • What should i use instead of quit? I saw that his line been weird... Explains why i get prime number on all numbers. But i know this code should work with just a small change! I just like how short it's possible to code in python! – Chris Lundin Dec 12 '22 at 14:33
  • Sorry no, but thanks for the share! Figure it out thanks – Chris Lundin Dec 12 '22 at 21:49

1 Answers1

0

There are couple of issue with your code. your break statement supressing the not prime print statemnt. Your print prime number is excluded from any loops hence it is printed every time.

Code correction

n = int(input("Enter a number: "))
for i in range(2, int(n/2)+1):
    if (n % i) == 0:    
        print(n, "is not a prime number")
        break
else:
    print(n, "is a prime number")

More simpler approch

n = int(input("Enter a number: "))
result = all(n % i for i in range(2, n))

if result:
    print(n, 'prime num')
else:
    print(n, 'not a prime num')