【问题标题】:How can I use user input to call functions?如何使用用户输入来调用函数?
【发布时间】:2020-05-06 13:05:10
【问题描述】:

我想使用用户输入调用函数。将要求用户从 n = 中进行选择,这将调用一个创建新行的函数,而 d 将调用另一个从用户输入中删除一行的函数。如果用户输入不在选项中,它将返回选项。

我需要使用“del”关键字创建一个函数来删除该行。但我不知道该怎么做。

def add(n):
    lines = list()
    add_line = input('Add a line: ')
    while add_line != '#':
        lines.append(add_line)
        add_line = input('Add a line: ')
    for line in lines:
        print(lines.index(line) +1, end = '')
        print(":", line)

def delete(d):


def main():
    choice= input ("Command n, d: ")
    for a in choice:
        add(n)

main()

我的输出应该是这样的:

Command n, d : n
Add a line: It is a lovely morning
Add a line: #
1: It is a lovely morning


Command n, d: d
Line number: 3
1: It is a lovely morning
2: for reading a book

【问题讨论】:

    标签: python python-3.x list function loops


    【解决方案1】:

    您需要将lines 设为全局或将其传递给删除函数。

    lines = list() # move this out of add
    def delete():
        global lines 
        line_no = input('line number to delete: ')
        del lines[int(line_no) - 1]
    
    def main():
        choice = input ("Command n, d: ")
        if "a" in choice:
            add()
        elif "d" in choice:
             delete()
    
    main()
    

    【讨论】:

    • 嗯,我试过这个,但它给了我一个错误,我输入的输入没有定义。
    • 现在它没有调用该函数。如果我尝试 for 循环,它会调用该函数,但我的问题是,当我将 d 放入用户输入时,它会从添加打印而不是直接删除
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 2013-05-13
    • 2016-06-21
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多