0

我无法创建一个非常简单的程序,该程序允许用户存储和编辑字符串,以列表格式查看(我几周前才开始编程)。每当我执行程序时,用户输入都不会编辑字符串。这是我的代码,下面是程序当前所做的事情,以及修补后我打算做什么(请注意,我没有收到任何错误)。

Code:

#Program that stores up to 5 strings

def main():
    line1="hello"
    line2=""
    line3=""
    line4=""
    line5=""
    print("[1]"+line1)
    print("[2]"+line2)
    print("[3]"+line3)
    print("[4]"+line4)
    print("[5]"+line5)
    print("")
    print("Which line would you like to edit?")
    lineChoice=''
    while lineChoice not in ('1', '2', '3', '4', '5'):
        lineChoice=input("> ")
    if lineChoice=="1":
        print("You are now editing Line 1.")
        line1=input("> ")
        main()
    if lineChoice=="2":
        print("You are now editing Line 2.")
        line2=input("> ")
        main()
    if lineChoice=="3":
        print("You are now editing Line 3.")
        line3=input("> ")
        main()
    if lineChoice=="4":
        print("You are now editing Line 4.")
        line4=input("> ")
        main()
    if lineChoice=="5":
        print("You are now editing Line 5.")
        line5=input("> ")
        main()

main()

这是我的程序所做的。

>>> ================================ RESTART ================================
>>> 
[1]hello
[2]
[3]
[4]
[5]

Which line would you like to edit?
> 1
You are now editing Line 1.
> hello world
[1]hello
[2]
[3]
[4]
[5]

Which line would you like to edit?
> 

这是我打算让我的程序做的事情。

>>> ================================ RESTART ================================
>>> 
[1]hello
[2]
[3]
[4]
[5]

Which line would you like to edit?
> 1
You are now editing Line 1.
> hello world
[1]hello world
[2]
[3]
[4]
[5]

Which line would you like to edit?
> 

如果我需要提供更多信息,我愿意。

  • 雅各布·登斯莫尔
4

1 回答 1

0

它实际上是因为您在main每次重置变量时递归调用。您需要做的是用循环替换递归main调用while。尽可能少地更改您的代码,它看起来像这样(假设您使用input的是 3.x 并因此使用):

def main():
    line1="hello"
    line2=""
    line3=""
    line4=""
    line5=""
    while True:
        print("[1]"+line1)
        print("[2]"+line2)
        print("[3]"+line3)
        print("[4]"+line4)
        print("[5]"+line5)
        print("")
        print("Which line would you like to edit?")
        lineChoice=''
        while lineChoice not in ('1', '2', '3', '4', '5'):
            lineChoice=input("> ")
        if lineChoice=="1":
            print("You are now editing Line 1.")
            line1=input("> ")
        if lineChoice=="2":
            print("You are now editing Line 2.")
            line2=input("> ")
        if lineChoice=="3":
            print("You are now editing Line 3.")
            line3=input("> ")
        if lineChoice=="4":
            print("You are now editing Line 4.")
            line4=input("> ")
        if lineChoice=="5":
            print("You are now editing Line 5.")
            line5=input("> ")

main()
于 2013-03-20T04:19:47.680 回答