代码之家  ›  专栏  ›  技术社区  ›  bot_diyar

如何给出错误而不是系统错误[重复]

  •  -1
  • bot_diyar  · 技术社区  · 6 年前

    嘿,我在python3中有了我的数字猜测器。但是如果用户键入字母而不是数字,我想给出一个错误。当我打一封信时,上面写着

    Traceback (most recent call last):
      File "nummerlol.py", line 14, in <module>
        guess = int(guess)
    ValueError: invalid literal for int() with base 10:"
    

    是否有方法更改此错误?thx公司

    import time
    import random 
    from secrets import randbelow
    guesscount = 0
    print("Hey whats your name")
    name = input()
    number = randbelow(20)
    print("The Number is between 1 & 20")
    while guesscount < 6:
        print("Guess.")
        guess = input()
        guess = int(guess)
        guesscount = guesscount + 1
        if guess < number:
            print("My Number is bigger")
        if guess > number:
            print("My Number is lower")
        if guess == number:
            break
    if guess == number :
    guesscount = str(guesscount)
    print("Nice",name ,".")
    print("You needed" ,guesscount ,"Tries")
    if guess != number:
        number = str(number)
        print("Bruh,My Number was" ,number)`
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   RuthC    6 年前

    您可以使用“尝试除外”循环。具有 continue (如下)用户可以继续猜测。您还可以将自己的异常替换为 print 持续 如果您希望脚本以更具信息性的消息中断。

    import time
    import random 
    from secrets import randbelow
    guesscount = 0
    print("Hey whats your name")
    name = input()
    number = randbelow(20)
    print("The Number is between 1 & 20")
    while guesscount < 6:
        print("Guess.")
        guess = input()
        try:
            guess = int(guess)
        except:
            print("That is not a number")
            continue
        guesscount = guesscount + 1
        if guess < number:
            print("My Number is bigger")
        if guess > number:
            print("My Number is lower")
        if guess == number:
            break
    if guess == number :
        guesscount = str(guesscount)
    print("Nice",name ,".")
    print("You needed" ,guesscount ,"Tries")
    if guess != number:
        number = str(number)
        print("Bruh,My Number was" ,number)
    
        2
  •  0
  •   Tasha R    6 年前

    A. similar question 你的问题已经存在了,但我还是会回答你的问题。

    正如您所知,您得到回溯响应的原因是因为您试图在调用时将非整数转换为整数 int(guess) 。可以使用try/except块捕获此异常。例如,您可以用以下代码替换有问题的代码行:

    while True:
      try:
        guess = int(guess)
        break
      except ValueError:
        print("You must enter a valid number.")
    

    此代码将导致程序要求用户输入,直到该输入有效。看看这条蟒蛇3 handling errors and exceptions 有关详细信息,请参阅文档。