繁体   English   中英

为什么 Python function 在不调用时执行?

[英]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.

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