[英]Why Python function executes when not called?
我是一名學習 Python 的學生。 我有一個處理數組的程序:
from array import *
adj_list = array('i', [])
def includeNode():
print('Enter the value')
k = int(input())
adj_list.append(k)
print('Your list:')
printList()
def includeNodeIndex():
print('Enter the value')
k = int(input())
print('Enter the index')
index = int(input())
adj_list.insert(index, k)
print('Your list:')
printList()
def deleteNode():
print('Enter the value')
k = int(input())
adj_list.remove(k)
print('Your list:')
printList()
def printList():
for i in adj_list:
print(i)
actions = {
'1': includeNode(),
'2': includeNodeIndex(),
'3': deleteNode()
}
print('Enter the number of elements')
num = int(input())
print('Enter ', num, ' elements')
for i in range(num):
k = int(input())
includeNode(k)
print('Your list:')
printList()
print('Enter 0 to exit. Enter 1 to delete an element. Enter 2 to add an element. Enter 3 to insert an element after index')
command = input()
while(command):
actions[command]
print('Enter 0 to exit. Enter 1 to delete an element. Enter 2 to add an element. Enter 3 to insert an element after index')
command = input()
我希望當我執行代碼時,它會 output Enter the number of elements
然后我就可以使用我的數組了。 但這不會發生。 相反,程序輸出Enter the value
:這意味着它執行了我什至沒有調用的includeNode()
function? 為什么會這樣? 這個 function 不應該在它被調用時執行(而不是在它被聲明時)?
當你放括號時,你實際上是在構建actions
字典時調用函數,所以
actions = {
'1': includeNode,
'2': includeNodeIndex,
'3': deleteNode
}
actions['1']()
input
允許將文本參數顯示給允許以下簡化的用戶
print('Enter the value')
k = int(input())
# into
k = int(input('Enter the value: '))
給予之類的東西
info_txt = 'Enter 0 to exit. Enter 1 to delete an element. Enter 2 to add an element. Enter 3 to insert an element after index'
command = input(info_txt)
while command:
actions[command]()
command = input(info_txt)
但請注意信息文本與actions
字典鍵映射不匹配
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.