在循环中放置一个Try和Except

时间:2016-10-23 12:10:54

标签: while-loop try-except python-3.5

嗨,我想弄清楚如何在while循环中放置'Try and Except'。我的兄弟要求我创建一个计算机程序创建一个随机数(1-100)然后用户尝试猜测它是什么。我设法让这个工作,但我坚持,如果用户实际上没有输入数字,我应该做什么,以便程序不只是停止工作,但只是提示用户他们做错了什么。下面我附上了我的完整代码。该程序有效,但我不知道如何将While循环放入其中。我已经尝试过像'猜猜!=整数'这样的事情,而且我一直在寻找不同的方法来解决这个问题。我见过的最好的就是有人只是说试着把它放到一个while循环中,但是它并没有告诉我怎么做。 try-except inside a loop。如果可能的话,我也想知道无论如何我都可以在用户回答的任何时候调用此循环,所以如果他们连续输入错误我不需要做任何其他事情。感谢您花时间阅读本文,抱歉,我写了很多

import random
import time
def guessMyNumber():
print("Hello , welcome to Guess My Number")
time.sleep(1)
print ("The computer is thinking of a number between 1-100")
time.sleep(2)
print("Try to guess the number in as few attempts as possible")
number=random.randint(1,100)
try:
    guess=int(input("Take a guess "))
except ValueError:
    print("You must enter a whole number")
    guess=int(input("Please take another guess, making sure that it is a whole number. Thank you. "))
 tries = 1
while guess !=number:
    if guess>number:
        print("You need to go lower")
        guess=int(input("Take a guess "))
    else:
        print("Go higher!")
        guess=int(input("Take a guess "))
    tries=tries+1
if tries < 5:
    print("Well done! You guessed the number in", tries, "tries! If you would like to play again please type 'guessMyNumber()'")
else:
        print("You guessed the number in", tries, "tries. If you would like to play again type 'guessMyNumber()' ")

guessMyNumber()

1 个答案:

答案 0 :(得分:0)

你的except块不应该引发异常,下面是你可以做int的一个例子,你可以根据你的程序要求进行修改

count = 0
while count < 5:
 try:
    guess=int(input("Take a guess "))
 except ValueError:
    print("You must enter a whole number")
    print("Please take another guess, making sure that it is a whole number. Thank you. ")
 count = count+1