【问题标题】:Input error recognized just first time, second time it starts to run第一次识别输入错误,第二次开始运行
【发布时间】:2016-12-11 17:36:28
【问题描述】:

当我尝试选择错误的选项时,它第一次给了我错误。第二次它开始运行“选择级别”块。例如,如果我输入选项“12”,程序会返回错误并让我再次选择,这次我输入“13”,它会返回“选择级别”块。我需要放一段时间或什么来验证选择吗?

import random
import sys

choice = None

while choice != "0":
     print('''
     --------------------
     Welcome to Hangman
     --------------------

     Please select a menu option:

     0 - Exit
     1 - Enter a new text file to be read:
     2 - Play Game

     ''')

choice= input("Enter you choice: ")

if choice == "0":
    sys.exit("Exiting from Python")

elif choice =="1":
    while True:
        try:
            fileInput = input("Enter a new text file name: ")
            List = open(fileInput).readlines()
            break
        except:
            print ("\n Failed to open the file")
            sys.exit()

elif choice == "2":
    List = open("words_for_hangman.txt").readlines()

elif choice == " ":
    choice = print("\n That is not a valit option! Please try again!")
    choice = input("Choice:")

else:
    choice = print("\n That is not a valid option! Please try again!")
    choice = input("Choice: ")

print('''

Now select your difficulty level:

0 - EASY
1 - INTERMEDIATE
2 - HARD

''')

level= input("Enter your choice: ")
if level == "0":
    word = random.choice(List)
    word = word.strip()
    hidden_word = "*" * len(word)
    lives = 10
    guessed = []
elif level == "1":
    word = random.choice(List)
    word = word.strip()
    hidden_word = "*" * len(word)
    lives = 7
    guessed = []
elif level == "2":
    word = random.choice(List)
    word = word.strip()
    hidden_word = "*" * len(word)
    lives = 5
    guessed = []


while lives != 0 and hidden_word != word:
    print("\n-------------------------------")
    print("The word is")
    print(hidden_word.replace("_"," _ "))
    print("\nThere are", len(word), "letters in this word")
    print("So far the letters you have guessed are: ")
    print(' '.join(guessed))
    print("\n You have", lives,"lives remaining")
    guess = input("\n Guess a letter: \n")
    guess = guess.upper()
    if len(guess) > 1:
        guess = input("\n You can only guess one letter at a time!\n Try again: ")
        guess = guess.upper()
    elif guess== " ":
        guess = input("\n You need to input a letter, not a space!\n Come on let's try again: ")
        guess = guess.upper()
    while guess in guessed:
        print("\n You have already guessed that letter!")
        guess = input("\n Please take another guess: ")
        guess = guess.upper()
    guessed.append(guess)
    if guess in word:
        print('''-------------------------------
        ''')
        print("Well done!", guess.upper(),"is in the word")
        word_so_far = ""
        for i in range (len(word)):
            if guess == str(word[i]):
                word_so_far += guess
            else:
                word_so_far += hidden_word[i]
        hidden_word = word_so_far
    else:
        print('''-------------------------------
        ''')
        print("Sorry, but", guess, "is not in the word")
        lives -= 1

if lives == 0:
    print("GAME OVER! You have no lives left")
else:
    print("\n CONGRATULATIONS! You have guessed the word")
    print("The word was", word)
    print("\nThank you for playing Hangman")

【问题讨论】:

  • 您的错误是,当用户输入错误时,您输入了一个可能再次错误的新输入。但你不检查。摆脱这种情况的一个好方法是在用户选择错误时恢复循环。详情见我的回答。

标签: python python-3.x error-handling


【解决方案1】:

是的,您的第二个输入实际上并没有得到检查。您需要将它放在一个 while 循环中,以便它始终返回相同的输入并再次执行所有检查:

goodChoice = false
while not goodChoice:
    #print text message
    choice = input("Enter you choice: ")
    if choice == 1:
        goodchoice = True

#game code

上面的(没有你的函数)将永远发生,直到输入一个选择 1,然后它会进入其余的代码

【讨论】:

    【解决方案2】:

    您需要继续循环,以便在输入错误时从用户那里获取下一个输入。

    if choice == "0":
        sys.exit("Exiting from Python")
    
    elif choice =="1":
        while True:
            try:
                fileInput = input("Enter a new text file name: ")
                List = open(fileInput).readlines()
                break
            except:
                print ("\n Failed to open the file")
                sys.exit()
    
    elif choice == "2":
        List = open("words_for_hangman.txt").readlines()
    
    elif choice == " ":
        choice = print("\n That is not a valit option! Please try again!")
        # continue the loop if the choice is wrong
        continue
    
    else:
        choice = print("\n That is not a valid option! Please try again!")
        # continue the loop if the choice is wrong
        continue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多