2013-03-20 59 views
0

我在创建一个非常简单的程序时遇到问题,该程序允许用户存储和编辑以列表格式(我几周前开始编程)查看的字符串。每当我执行程序时,用户输入都不会编辑字符串。这是我的代码,下面是该程序目前的功能,以及一旦打补丁后我打算做的事情(请注意,即使没有错误)。Python - 将用户可编辑字符串存储到列表中的问题

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? 
> 

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

  • 雅各布·登斯莫尔
+1

1.你(重新)定义line1,2,3, 4,5每当你输入main(); 2.你没有使用列表,你只是使用了一堆类似的命名字符串; 3.您可以将所有嵌入“if”语句中的'main'的调用缩减为最后一次调用。 – 2013-03-20 04:19:46

回答

0

它实际上是因为你是如此的每次递归调用main的变量被重置。您需要做的是用while循环替换递归调用main。改变你的代码尽可能少的,它应该是这样的(假设你是在3.x和使用input因为这个原因):

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() 
+0

工作正常!谢谢。我很惊讶,我没有看到这个问题。 – dudens97 2013-03-20 05:05:54

相关问题