【问题标题】:Why Python function executes when not called?为什么 Python 函数在未调用时执行?
【发布时间】:2021-07-12 03:07:07
【问题描述】:

我是一名学习 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()

我希望当我执行代码时,它会输出Enter the number of elements,然后我就可以使用我的数组了。但这不会发生。相反,程序输出Enter the value:这意味着它执行了我什至没有调用过的includeNode() 函数! 为什么会这样?这个函数不应该在它被调用的时候执行(而不是在它被声明的时候)?

【问题讨论】:

  • 你在那里称呼它:actions = { '1': includeNode(), '2': includeNodeIndex(), '3': deleteNode() }
  • 您也不需要使用array 模块。您可能来自其他语言,其中“数组”是您通常表示事物数组的方式。在 Python 中,we have/use lists.

标签: python arrays function


【解决方案1】:

当你放括号时,你实际上是在构建actions dict时调用函数,所以

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 dict 键映射不匹配

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2021-01-06
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多