![](/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.