繁体   English   中英

Python 全局和局部变量:代码是如何工作的?

[英]Python global and local variable: How does the code work?

我遇到了一个允许用户输入水果名称的代码。 根据输入,将从篮子列表中搜索它,如果水果在列表中,则显示其数量。

如果没有找到水果,用户可以输入该水果的数量并将其添加到列表中。

basket = [
    {'fruit': 'apple', 'qty': 20},
    {'fruit': 'banana', 'qty': 30},
    {'fruit': 'orange', 'qty': 10}
]

fruit = input('Enter a fruit:')

index = 0
found_it = False

while index < len(basket):
    item = basket[index]
    # check the fruit name
    if item['fruit'] == fruit:
        found_it = True
        print(f"Basket has {item['qty']} {item['fruit']}(s)")
        break

    index += 1

if not found_it:
    qty = int(input(f'Enter the qty for {fruit}:'))
    basket.append({'fruit': fruit, 'qty': qty})
    print(basket)

但我不明白外部 if 条件的逻辑。 它指的是哪个found_it 在(全局)while 语句之前定义的一个还是在其中定义的一个(本地)? 外部if如何工作的?

在 python 中,您没有显式声明变量。 这可能会造成混淆,但是一旦 scope 中存在变量,在这种情况下是全局变量,那么分配给它会改变它的值,而不是创建一个新变量。 最好的时刻是当你拼错一些东西时,python 会认为你用那个值声明了新变量,而原来的变量不会改变。 我真的不明白为什么 python 的创建者会引入这种歧义,幸运的是新语言正在避免这个错误。

这并不是真正的答案,而是向您展示了如何回避使用可变值来决定下一步该做什么的问题。


请注意,Python 有一个while-else结构,这使得found_it变量变得不必要。

basket = [
    {'fruit': 'apple', 'qty': 20},
    {'fruit': 'banana', 'qty': 30},
    {'fruit': 'orange', 'qty': 10}
]

fruit = input('Enter a fruit:')

index = 0

while index < len(basket):
    item = basket[index]
    # check the fruit name
    if item['fruit'] == fruit:
        print(f"Basket has {item['qty']} {item['fruit']}(s)")
        break

    index += 1
else:
    qty = int(input(f'Enter the qty for {fruit}:'))
    basket.append({'fruit': fruit, 'qty': qty})
    print(basket)

循环的else子句仅在没有使用break退出循环时执行,即当您更改found_it的值时。


有点不相关,您可以直接遍历basket的元素,而无需使用索引。

basket = [
    {'fruit': 'apple', 'qty': 20},
    {'fruit': 'banana', 'qty': 30},
    {'fruit': 'orange', 'qty': 10}
]

fruit = input('Enter a fruit:')

for item in basket:
    # check the fruit name
    if item['fruit'] == fruit:
        print(f"Basket has {item['qty']} {item['fruit']}(s)")
        break
else:
    qty = int(input(f'Enter the qty for {fruit}:'))
    basket.append({'fruit': fruit, 'qty': qty})
    print(basket)

else的行为方式与forwhile相同:它仅在循环“自然”退出时执行,在这种情况下,通过耗尽迭代器而不是当循环条件变为 false 时执行。

使用调试器运行代码表明,一旦遇到第一个found_it ,它就会在全局和本地创建,因此内部循环中的found_it会更改您最初声明的值。

调试器屏幕截图

关于外循环的工作, if not是检查真假的条件,即只有当值为假时才会执行。

使用常规的if-else会更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM