简体   繁体   中英

checking whether a number is prime

i am trying to create a for loop that goes through numbers in within range and check if they are divisible. Here is my code:

user_input = input("pick a number")

for i in range(1, int(user_input)):
    if int(user_input) % i == 0 and i != 1 and i != int(user_input):
        print("Your number is prime")
    else:
        print("your number is not prime")

the second condition keeps getting executed even for prime numbers. What am I doing wrong?

When you use a for loop, you are iterating the number of times that are in range(1, int(user_input)) and so your if/else gets executed over and over again, and in each iteration is printing something. Instead you only want to print when you are done.

To pull this off, you want to use a boolean True/False variable to track if the number is prime or not, and set it accordingly in your for loop.

user_input = input("pick a number")

is_prime = True
for i in range(2, int(user_input)):
    if int(user_input) % i == 0 :
        is_prime = False
        break #break out of the for loop since the number isn't prime

if is_prime:
   print("Your number is prime")
else:
   print("your number is not prime")

Some other small changes:

  1. Removed condition and i != 1 as any iteration past 1 would fail this test and you want to check EVERY number in your iterations
  2. Removed condition and i != int(user_input) since in your iterations you will never reach this number range() is not inclusive of the highest number.
  3. Added a break once we determine that the number is not a prime so we don't waste iterations checking if it's even more not-prime.

There are some issues with your code range should be 2 not 1. Add a break statemnt once condition satisfies.

user_input = input("pick a number")
user_input  = int(user_input)

for i in range(2, user_input)::  #for i in range(2, int(user_input /2)+1) also works
    if (user_input  % i) == 0:    
        print("Your number is prime")
        break
else:
    print("Your number is not a prime")

More simpler approch

user_input = int(input("pick a number"))
result = all(user_input % i for i in range(2, user_input))

if result:
     print("Your number is prime")
else:
     print("Your number not a is prime")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM