Home > Back-end >  Python - for-loop does not enter correct argument for boolean parameter
Python - for-loop does not enter correct argument for boolean parameter

Time:04-08

I am trying to generate a for-loop in Python that should classify any number as prime/not prime. The suggested command is:

def prime_checker(number):
  is_prime = True
  for n in range(2, number):
    if number % n == 0:
      is_prime = False
  if is_prime == True:
    print("It is a prime number.")
  else:
    print("It is not a prime number.")

The suggested command above works well. However, I would like to generate the parameter as is_prime = bool() (i.e. with no standard value), and only after that the function will classify is_prime as either "True" or "False". The reason is that I do not like the idea of generating variables with standard arguments; instead I prefer to first generate variables populated with missing values, and only then to have them filled in with the proper argument. I tried this command, but it will output only "It is a prime number.":

def prime_checker(number):
  is_prime = bool()
  for n in range(2, number):
    if number % n == 0:
      is_prime = False
    else:
      is_prime = True
  if is_prime == True:
    print("It is a prime number.")
  else:
    print("It is not a prime number.")

I wonder if anybody knows why the command above will output only "It is a prime number."

CodePudding user response:

I'm not sure why you don't like this idea, it is pretty standard in python (and in programmation in general) and often used. Anyway, the closest thing you could write would be:

is_prime = None

which is the equivelent in python to declaring a variable without assigning a value.

CodePudding user response:

It's because you're checking every number in the loop and assigning is_prime from that. This means the only comparison that will actually matter is the last one; i.e. number - 1 will always determine what it prints out.

As well your change does indeed have a default value. bool() will default to False

CodePudding user response:

It's because your second function does

else:
    is_prime = True

within the for-loop. So if it discovers that it's not a prime number for one value of n, the next iteration(n 1) might make it the is_prime equal to True.

For example, if you're testing the number 4:

  1. It's divisible by 2, so set is_prime to False
  2. It's not divisible by 3, so set is_prime to True

You need to add a break after you discover it's not prime, so that it won't try and keep checking other numbers.

And doing is_prime = bool() sets it to False, anyway.

  • Related