codingproject
codingproject

Reputation: 11

updating the value of a variable inside of a function

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)

Upvotes: 0

Views: 50

Answers (1)

Mustafa
Mustafa

Reputation: 61

...  

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)
...

Upvotes: 1

Related Questions