Skip to main content
 首页 » 编程设计

python之无法在 while 循环中更改全局变量

2025年02月15日9bluestorm

我正在尝试计算出条形码的最后一位数字,但是我在处理第二个和最后一个 while 循环时遇到了问题。

它们不会为变量 total 或 mOf10 分配任何新值。它反而将它们保留为 0,我不明白为什么。

while True: 
 
    number = input("Enter a 7 digit number please.") 
    if len(number) == 7: 
        try: 
            number = int(number) 
        except ValueError: 
            print("Please enter a number") 
        else: 
            break 
    else: 
        print("Please enter a valid number.") 
 
print(number) #DELETE THIS BIT LATER! 
i = 0 
total = 0 
 
while (i < 7 == True): 
    global total 
    f = str(number)[i] 
    if int(f) % 2 == 1: 
        total = total + int(f) * 3 
    else: 
        total = total + int(f) 
    i += 1 
 
print(total) 
 
mOf10 = 0 
 
while True: 
    global mOf10 
    if mOf10 >= total: 
        break 
    else: 
        mOf10 += 10 
 
finalD = mOf10 - total 
print(finalD) 

它会打印出您输入的 7 位数字,但它不会输出 10 的总数或 10 的倍数。他们只是以 0 出现。

我的老师对此唯一的解决方案是大量的 if/else 语句。

请您参考如下方法:

我不确定你到底想在这里做什么,但我可以告诉你 total 的值是什么问题。没有改变。这里的问题是在 condition对于 while环形。即 while (i < 7 == True) .

>>> i<7 
True  
>>> i<7 == True 
False 

如您所见,当条件返回 False 时,控件永远不会进入 while 循环.

相反,只需执行 while(i<7) .这应该可以解决它。

注意:使用global在代码中是错误的,因为total的范围和 mOf10本身就是本地的。

编辑: 奇怪行为的原因是由于比较运算符具有相同的优先级,并且由于运算符的链接,在 python 中类似于 x < y <= z。相当于x < y and y <= z .

According to Python docs :

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

我们在这里知道:

>>> i < 7 
True 
>>> 7 == True 
False 

并且由于运算符的链接,整个条件又变成了 i < 7 and 7 == True .自 7==True是False , 最后的条件计算为 False .