首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Try Except Block not passing Except

Try Except Block not passing Except
EN

Stack Overflow用户
提问于 2020-03-29 15:41:36
回答 2查看 37关注 0票数 0

我是Python和编码的新手,在我的代码中遇到了一些bug。每当我在Try/Except代码块中输入错误的输入时,控制台都会打印"Invalid input“,但是,每当我在控制台中输入正确的短语时,它仍然显示"Invalid input”。我在网上查看了一下,试图用这几行代码解决这个问题(用##表示),但我仍然得到了同样的问题。

例如,我输入了大小写正确的"Mad Libs“,但仍然从我的!=命令中得到了”无效输入“。通过以不同的方式格式化可以很容易地解决这个问题吗?这在所有3场比赛中都会发生。

如何解决这个问题?提前感谢!

代码语言:javascript
复制
def game_selection(): ##
    pass ##


while True: ##
    try:
        playerChoice = input("So, which game would you like to play?: ")
        if playerChoice != "Mad Libs":
            print("Invalid input")
        elif playerChoice != "Guessing Game":
            print("Invalid input")
        elif playerChoice != "Language Maker":
            print("Invalid input")
        continue ##
    except:
        print("Invalid Input")


game_selection() ##

print("Got it! " + playerChoice + " it is!")
sleep(2)

if playerChoice == "Mad Libs":
    print("Initializing 'Mad Libs'.")
    sleep(.5)
    print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
    print("All you have to do is enter in a phrase or word that is requested of you.")
    playerReady = input("Ready to begin? Y/N")
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-29 15:53:46

问题是,这个代码不会工作,因为如果我输入"Mad Libs“,第一个if将不会通过,因此它将传递给所有其他elif。所以你不能采用这种方法。我建议您做的是检查playerChoice字符串是否在数组中

代码语言:javascript
复制
from time import sleep

while True:
   playerChoice = input("So, which game would you like to play?:")
   allowedGames = ["Mad Libs", "Guessing Game", "Language Maker"]
   if playerChoice not in allowedGames:
      print('Invalid input!')
   else:
      break

print("Got it! " + playerChoice + " it is!")
sleep(2)

if playerChoice == "Mad Libs":
    print("Initializing 'Mad Libs'.")
    sleep(.5)
    print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
    print("All you have to do is enter in a phrase or word that is requested of you.")
    playerReady = input("Ready to begin? Y/N")
票数 0
EN

Stack Overflow用户

发布于 2020-03-29 15:51:01

因为您要求它在此代码中回答无效输入

代码语言:javascript
复制
While True: ##
    try:
        playerChoice = input("So, which game would you like to play?: ")
        if playerChoice != "Mad Libs":
            print("Invalid input")
        elif playerChoice != "Guessing Game":
            print("Invalid input")
        elif playerChoice != "Language Maker":
            print("Invalid input")
        continue ##
    except:
        print("Invalid Input")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60911384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档