python-3.x 更新函数内部的变量值

zi8p0yeb  于 2022-11-26  发布在  Python
关注(0)|答案(1)|浏览(147)

每次我试图在函数modulus中使用变量i时,它都会将该变量设置为0。
我试着用了一行代码:newi = i,但那不起作用,因为i已经等于0。我在模数函数中尝试了i = i,但那也不起作用。我尝试在程序顶部定义ia,但那不起作用。我希望通过运行primeChecker函数来改变i,但是值变成了0。我不知道为什么它是0,因为我没有在代码中的任何地方设置i = 0
编码:

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

w6lpcovy1#

...  

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

...

for”循环将i设置为0。您可以通过添加print语句来查看

...
i = 3
a = 0

print(i)

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

print(i)
...

相关问题