Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
异常处理-Python_Python_Exception_Try Catch - Fatal编程技术网

异常处理-Python

异常处理-Python,python,exception,try-catch,Python,Exception,Try Catch,当用户没有输入正确的字符时,我试图获取消息“INVALID VALUE”,但程序在没有打印消息的情况下重新启动。你能帮我吗 # Print "Male" when the user types "M" and "Female" when the user types "F" def m_ou_f(): mens_erro = "INVALID VALUE" while True: try: sex = str(input("Type M

当用户没有输入正确的字符时,我试图获取消息“INVALID VALUE”,但程序在没有打印消息的情况下重新启动。你能帮我吗

# Print "Male" when the user types "M" and "Female" when the user types "F"

def m_ou_f():
    mens_erro = "INVALID VALUE"
    while True:
        try:
            sex = str(input("Type M for Male or F for Female: "))
            sex == "M" or sex == "F" or sex == "f" or sex == "m"
        except:
            print(mens_erro)
            continue
        else:
            return sex
            break

while True:
    sex = m_ou_f()
    try:
        sex == "M" or sex == "F" or sex == "f" or sex == "m"
    except:
        print("INVALID VALUE!")
        continue
    else:
        if sex == 'M' or sex == 'm':
            print("Male")
            break
        elif sex == 'F' or sex == 'f':
            print("Female")
            break

同样的东西不需要写两遍

声明的作用如下。[来自Python文档]

  • 首先,执行try子句(try和except关键字之间的语句)

  • 如果未发生异常,则跳过except子句并完成try语句的执行

  • 如果在执行try子句期间发生异常,则跳过该子句的其余部分。然后,如果其类型与以except关键字命名的异常匹配,则执行except子句,然后在try语句之后继续执行

  • 如果发生与EXPECT子句中指定的异常不匹配的异常,则将其传递给外部try语句;如果未找到处理程序,则它是一个未处理的异常,执行将停止,并显示一条消息,如上所示

在您的例子中,try块已成功执行,这就是它未进入execast块的原因

这将打印
无效值

为True时:
尝试:
性别=str(输入(“男性输入M,女性输入F:”)
除值错误外:
打印(“无效值!”)
如果性别='M'或性别='M':
印刷品(“男性”)
打破
elif sex='F'或sex='F':
印刷品(“女性”)
打破
其他:
打印(“无效值!”)
如果我需要补充更多解释,请告诉我

sex == "M" or sex == "F" or sex == "f" or sex == "m"
此行不会引发异常——如果键入了错误的字符,它将计算为“false”

也许你想要这样的东西:

if sex == "M" or sex == "F" or sex == "f" or sex == "m" : raise Exception(mens_erro) 
至于第二部分——您的函数不会返回异常,因此无需将其放入try-catch:

while True:
    sex = m_ou_f()
    if sex == 'M' or sex == 'm':
        print("Male")
        break
    elif sex == 'F' or sex == 'f':
        print("Female")
        break
但如果你做到了:

try:
  sex = m_ou_f();
except:
  continue

你熟悉try/except的基本知识吗?另外,在使用
时要小心,除非:
如下所示,请参阅。