【发布时间】:2015-10-15 13:22:16
【问题描述】:
谁能帮我理解以下问题...
我在简单的猜数字游戏中执行 try/except 块时遇到问题。如果我删除初始输入的整数部分,包含我的错误处理的函数可以正常工作。但是如果我这样做,游戏的其余部分就不起作用,因为根据我的理解,Python3 接受输入并将其存储为字符串。那么我怎样才能让我的异常执行呢?非常感谢任何帮助。
谢谢,
# number game
import random
print ("Welcome to the guessing number game!\n\n")
winning_number= random.randrange(1, 11)
guess = int(input("Can you guess the lucky number.\nHint it's between 1 and 10!\n"))
def is_number(guess):
try:
int(guess)
except ValueError:
print ('You need to type a number\n')
guess = int((input("Please input a number\n")))
game(guess)
def compare(guess):
if guess > winning_number:
print ("Wrong, you're guess is too high.\n")
guess = int(input("Guess againn\n"))
game(guess)
else:
print ("Wrong, you're guess is too low.\n")
guess = int(input("Guess again\n"))
game(guess)
def game(guess):
is_number(guess)
if guess == winning_number:
print ("You win!, You guessed the number!")
else:
compare(guess)
game(guess)
这是我输入除整数以外的任何内容时得到的结果...
欢迎来到猜数字游戏!
你能猜出幸运数字吗? 提示它在 1 到 10 之间! F 回溯(最近一次通话最后): 文件“C:/Users/mickyj209/PycharmProjects/Practice/NumberGuess.py”,第 10 行,在 guess = int(input("你能猜出幸运数字吗?\n提示它在 1 到 10 之间!\n")) ValueError: int() 以 10 为底的无效文字:'f'
进程以退出代码 1 结束
【问题讨论】:
-
您遇到了什么问题?
-
如果初始输入不是整数,则我的函数的 except 部分不会按应有的方式执行。我仍然得到一个 ValueError。
-
您的游戏看起来不错,请分享导致问题的输入
-
未来的提示:
random.randint更适合分配winning_number。 -
将我的错误添加到帖子中......
标签: python python-3.x error-handling try-catch except