运行此代码时,我一直收到一个未定义的错误

时间:2015-03-27 00:36:16

标签: python try-catch undefined

import sys                                                                                                                                          
looptwo = True
while looptwo == True:
  print("Welcome to the junior maths program, this program helps you do    maths problems and acts as a calulator.")                                      
  try:
    name = input("What is your name? ")                                                                                                             
    number = int(input("Enter your first number: "))                                                                                                
    number2 = int(input("Enter your second number: "))
  except ValueError:
    print("that is not an option")
    looptwo == False

当我运行此代码时,它表示该数字未定义。

1 个答案:

答案 0 :(得分:2)

你的逻辑是倒退的,你应该只在没有错误的情况下中断,你设置looptwo等于False,除非假设==是打破循环的拼写错误。因此,每当您尝试访问name等外部异常后的循环时,您将收到一个未定义的错误。 代码中断的唯一方式是引发异常时:

使用True,只有在没有例外时才会中断。

while True:
    print("Welcome to the junior maths program, this program helps you do    maths problems and acts as a calulator.")
    try:
        name = input("What is your name? ")
        number = int(input("Enter your first number: "))
        number2 = int(input("Enter your second number: "))
        break
    except ValueError:
        print("that is not an option")