![](/img/trans.png)
[英]How does Python recognize whether a variable in a function is global or local?
[英]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
的行为方式与for
和while
相同:它仅在循环“自然”退出时执行,在这种情况下,通过耗尽迭代器而不是当循环条件变为 false 时执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.