2016-07-27 45 views
2

简单的问题,但它使我疯了。为什么当我运行这个代码时,它只是不断重复自己?而且我的缩进是正确的,只是不得不将空间放置4次,无论出于何种原因。虽然Python循环不断重复自己

高分

0 - 退出 1 - 显示比分

的源代码:

scores = [] 

choice = None 
while choice != "0": 

    print(
    """ 
    High Scores 

    0 - Exit 
    1 - Show Scores 
    """ 
    ) 

    choice = input("choice: ") 
    print() 

    if choice == "0": 
     print ("exiting") 

    elif choice == "1": 
     score = int(input("what score did you get?: ")) 
     scores.append(score) 

    else: 
     print ("no") 

    input ("\n\nPress enter to exit") 
+0

你_sure_你正在运行的Python 3? –

+0

sayan 98是我的while循环下的身份。谢谢 –

+0

@JacobMoore乐于帮忙! – sayan

回答

1

这是因为您没有使用正确的缩进。请在您要执行的w​​hile循环下缩进代码while choice != 0

此外,由于您将字符串作为输入而不是Int,错误地指示了@ wookie919,所以比较没有任何错误。然而,你可以将你的输入以字符串形式包装在int()中,如int(input("Choice .. "))

希望它有帮助。

0

这是因为你在比较的整数的字符串。尝试输入"0"而不是0。或者修改你的程序,与0而不是"0"进行比较。

+0

OP将int与字符串进行比较在哪里? –

+0

@ Two-BitAlchemist尝试OP的代码后,这是一个有教养的猜测。 – wookie919

-1
scores = [] 

choice = None 
while choice != "Exit": 

    print("High Scores\n0 - Exit\n1 - Show Scores") 

    choice = input("choice: ") 

    if choice == "0": 
     print ("exiting") 

    elif choice == "1": 
     try: 
      score = int(input("What score did you get?: ")) 
      scores.append(score) 
     except: 
      print('INVALID INPUT') 
    else: 
     print('INVALID INPUT') 

    choice = input ("\n\nPress enter to exit: ") 
    choice = "Exit" 
+0

你应该看到我的其他答案。它在错误处理方面做得更好。 –

+0

将来,您应该通过这个步进工具运行有问题的代码。它会帮助你: http://www.pythontutor.com/visualize.html#mode=edit –

-1

你也可以做到这一点,这是比我最后的答案更好:

scores = [] 

def user_choice(): 
    choice = None 
    while choice != "Exit": 

     print("High Scores\n0 - Exit\n1 - Show Scores") 

     choice = input("Choice: ") 

     if choice == "0": 
      print ("Exiting...") 
      return None 

     elif choice == "1": 
      try: 
       score = int(input("\nWhat score did you get?: ")) 
       scores.append(score) 
       go_on = input("\nEnter 'y' to go back or anything else to exit: ") 
       if go_on == "y": 
        user_choice() 
       else: 
        print('Exiting...') 
        choice = "Exit" 
      except: 
       print('\nINVALID INPUT\n') 
       user_choice() 
     else: 
      print('\nINVALID INPUT\n') 
      user_choice() 


     choice = "Exit" 

user_choice()