0

Every time I try to use the variable i in the function modulus, it sets the variable to equal 0.

I tried using the line of code: newi = i, but that didn't work because i was already equal to 0. I tried i = i in the modulus function, but that also didn't work. I've tried defining both i and a at the top of the program, that didn't work. I'm expecting i to change by running the primeChecker function, but the value becomes 0. I have no idea why it is 0 because I did not set i = 0 anywhere in my code.

Code:

number = input("How many numbers? ")
intnumber = int(number)
modulus = {}
modulusCounter = 0
exceptionPrime = [2]
prime = [3, 5, 7]
print("lengthprime", len(prime))

def modulus(i, a):
    print("i:", i)
    print(prime)
    print("modulus", prime[a])
    i % (prime[a])

def primeChecker(i, a, prime, modulusCounter):
    print("2 check")
    print("a value: ", a)
    print("prime: ", len(prime))

    for a in range(len(prime)):
        print("3 check")
        print("a: " + str(a))
        print("lengthprime: ", len(prime))

        if modulus(i,a) == 0:
            i += 2
            modulusCounter += 1
            print("1 check")

        else: #elif modulus(a,i) != 0:
            a += 1
            print("2 check")

    if a == len(prime) and modulusCounter == 0:
        print("Prime: ", i)
        print("3 check")
        prime.append(i)         
        i += 1
        modulusCounter = 0          
        a = 0

i = 3
a = 0

for i in range(intnumber):
    print("1 check")
    primeChecker(i, a, prime, modulusCounter)

print(prime)
9
  • The last line of modulus doesn't do anything useful. i itself isn't changed, and you don't do anything with the value of the expression. Commented Nov 20, 2022 at 20:38
  • 1
    modulus isn't returning anything Commented Nov 20, 2022 at 20:38
  • 2
    Certainly the first time through: for i in range(intnumber) this sets i=0 Commented Nov 20, 2022 at 20:41
  • How do I return something from a function? Commented Nov 20, 2022 at 21:07
  • Use the return keyword? Commented Nov 20, 2022 at 21:09

1 Answer 1

1
...  

i = 3
a = 0
    
for i in range(intnumber):
    print("1 check")
    primeChecker(i, a, prime, modulusCounter)

...

The "for" loop is setting i to 0. You can see for yourself by adding print statements

...
i = 3
a = 0

print(i)

for i in range(10):
    print(i)
    # ...your code

print(i)
...
Sign up to request clarification or add additional context in comments.

1 Comment

Which leads to a useful rule: never reuse your variable names. For loop counters that you don't need to refer to anywhere in the code, a helpful convention is to use for _ in ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.