2017-06-03 52 views
-1

我写了一个程序,生成一个随机数供用户猜测。我正在努力尝试捕捉所有可能的错误。唯一我无法想象的是这个。在开始时,我要求用户按回车继续游戏。如果程序输入一个字符串甚至是特殊字符和标点符号,该程序就会捕获。我似乎无法预防的唯一事情是,如果他们键入一个数字,程序就会终止。这是我的。问题出在try块的第一个while循环中。任何建议或帮助,将不胜感激。 在此先感谢。Python catch int或str

from random import randint #imports randint from random class 

cont = input('Press enter to continue') 

while True: 
    if cont != '': 
     try: 
      int(cont) 
      str(cont) 
      break 
     except ValueError: 
      print('Just hit enter') 
      cont = input() 
      continue 
    elif cont == '': 
     while True: 

      randNum = randint(1, 100) 
      print('Try guesssing a number between 1 and 100') 
      num = input() 

      while True: 
       try: 
        int(num) 
        break 
       except ValueError: 
        print('Please enter a number') 
        num = input() 

       int(num) 
      if num == randNum: 
       print('Good job, ' + str(num) + ' is correct.') 
      else: 
      print('Sorry, the number was ' + str(randNum) + '.') 

     print('Would you like to try again?') 
     answer = input().lower() 
     if answer == 'yes': 
      continue 
     elif answer == 'no': 
      print('Thanks for playing') 
      exit() 
     else: 
      while True: 
       print('Please type yes or no') 
       answer = input() 
       if answer == 'yes': 
        break 
       elif answer == 'no': 
        print('Thanks for playing.') 
        exit() 

回答

1

当你输入一个号码是程序试图转换为int数(工作)会发生什么,然后到str(这也适用)后,它打破了。相反,尝试以下操作:

from random import randint #imports randint from random class 

cont = input('Press enter to continue') 

while cont != '': 
    cont = input('Press enter to continue') 

while True: 

    randNum = randint(1, 100) 
    print('Try guesssing a number between 1 and 100') 
    num = input() 

    while True: 
     try: 
      int(num) 
      break 
     except ValueError: 
      print('Please enter a number') 
      num = input() 

     num = int(num) 
    if num == randNum: 
     print('Good job, ' + str(num) + ' is correct.') 
    else: 
    print('Sorry, the number was ' + str(randNum) + '.') 

print('Would you like to try again?') 
answer = input().lower() 
if answer == 'yes': 
    continue 
elif answer == 'no': 
    print('Thanks for playing') 
    exit() 
else: 
    while True: 
     print('Please type yes or no') 
     answer = input() 
     if answer == 'yes': 
      break 
     elif answer == 'no': 
      print('Thanks for playing.') 
      exit() 
+0

我正试图以不同的方式来捕捉错误,但这是有效的。谢谢。 – kfreeman04208

+0

@ kfreeman04208没问题:) –

+0

有没有可能解释为什么我的方法能够捕捉除数字之外的所有内容? – kfreeman04208

-1
while True: 
    if cont != '': 
     try: 
      int(cont) 
      str(cont) 
      break 

它这里什么是尝试和转换cont为int,如果成功,它试图将其转换为一个字符串(这几乎是总是可能的)。如果成功,它会中止while循环并结束程序。 在尝试解析它时,除int以外的任何其他场景中int(cont)它会引发错误,并且继续执行程序。

一旦他按下输入cont就会开始。在输入文本之前,没有理由确认他没有写任何东西。

相关问题