1
from sys import argv

def prime():
  for i in range(2,num):
      if num % i == 0:
          print(f"{num} can be divisible by {i}.")
          checker = False

num = int(input("Enter the number you want to check is prime: "))
checker = True

if num < 2:
    print(f"{num} is a prime number.")
elif num == 0:
    print(f"{num} is not a prime number.")
elif num > 0:
    prime()
    print(f"Is this number a prime - {checker}.")
else:
    print(f"Please write number larger than 0.")

Hello guys, I've just started to code and this is probably a really simple question. I want my code to either find the factors of a number or print if a number is a prime - but my boolean value in the "prime" function never updates to False. Not sure why!

Thank you.

lyxαl
  • 1,108
  • 1
  • 16
  • 26
tobytobias
  • 61
  • 10

2 Answers2

0

The reason why your prime() function is not 'updating' to False is because there is no return statement in the function.

With it, the function looks like this:

def prime():
  checker = True
  for i in range(2,num):
      if num % i == 0:
          print(f"{num} can be divisible by {i}.")
          checker = False
  return checker

And the updated code looks like this:

from sys import argv

def prime():
  checker = True
  for i in range(2,num):
      if num % i == 0:
          print(f"{num} can be divisible by {i}.")
          checker = False
  return checker


num = int(input("Enter the number you want to check is prime: "))

if num < 2:
    print(f"{num} is a prime number.")
elif num == 0:
    print(f"{num} is not a prime number.")
elif num > 0:
    is_prime = prime()
    print(f"Is this number a prime - {is_prime}.")
else:
    print(f"Please write number larger than 0.")

However, this isn't the only way to solve your problem: it's not recommended and frowned upon by many programmers as bad practice - use the global statement (which looks like that's what you were trying to do originally).

With it, the function looks like this:

def prime():
  global checker
  for i in range(2,num):
      if num % i == 0:
          print(f"{num} can be divisible by {i}.")
          checker = False

And the updated code looks like this:

from sys import argv

def prime():
  global checker
  for i in range(2,num):
      if num % i == 0:
          print(f"{num} can be divisible by {i}.")
          checker = False


num = int(input("Enter the number you want to check is prime: "))
checker = True

if num < 2:
    print(f"{num} is a prime number.")
elif num == 0:
    print(f"{num} is not a prime number.")
elif num > 0:
    prime()
    print(f"Is this number a prime - {checker}.")
else:
    print(f"Please write number larger than 0.")
lyxαl
  • 1,108
  • 1
  • 16
  • 26
0
def prime():
       global checker
       """ remaining logic as is"""

I think this would work. Sorry for format as I'm writing on phone.

Niranjan Agnihotri
  • 916
  • 2
  • 11
  • 19