我创建了一个简单的数字猜谜游戏,并且尝试修复无意输入的错误。
当程序要求进行猜测时,如果用户按回车键而不输入数字,则会出现此错误:
回溯(最近通话最近):文件 “ / Users / tom / Documents /使用Python / RandomNumberGame.py自动化”,行 13,在 guess = int(input())ValueError:int()以10为底的无效文字:''
我希望它打印“请输入数字”。
我是编程的新手,已经开始阅读“使用Python自动化无聊的东西”。预先感谢!
原始代码不包含
elif guess == ' ':
print('Please enter a number')
但是目标是让程序说输入是否为空
我尝试添加:
guess = int(input()) or str(input())
没有任何进展
import random
print('Hello, What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 1000, You have 10 guesses to figure it out. Good luck!')
secretNumber = random.randint(1,1000)
print('DEBUG: Secret number is ' + str(secretNumber))
for guessesTaken in range(1,11):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
elif guess == ' ':
print('Please enter a number')
else:
break #This condition is for the correct guess
if guess == secretNumber:
print('Good job ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses!')
else:
print('Too many guesses, The number I was thinking of was ' + str(secretNumber))
答案 0 :(得分:0)
变量guess
是整数值,因为您正在将输入转换为整数guess = int(input())
。如果输入是空格或任何其他无效字符串(无法解析为数字),则会引发ValueError exception
-这就是收到该错误消息的原因。
您可以使用try/except
块来处理Python中何时发生特定异常。它的工作原理如下:
try:
# execute some code
except SomeException:
# handle the exception
将尝试执行try
块中的代码,并且如果运行该代码导致引发SomeException
异常,则将运行except
块中的代码。
在您的特定情况下,您想要做的是处理ValueError
异常,因此您可以像这样将相关代码包装在try/except
中:
...
for guessesTaken in range(1,11):
print('Take a guess.')
try:
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
elif guess == ' ':
print('Please enter a number')
else:
break #This condition is for the correct guess
except ValueError:
print('Please enter a number')
...
如果您希望无效输入不引起猜测,则可以像这样实现游戏:
...
guessesTaken = 1
while True:
print('Take a guess.')
try:
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
elif guess == ' ':
print('Please enter a number')
else:
break #This condition is for the correct guess
except ValueError:
print('Please enter a number')
continue # go back to the start of loop (without incrementing guessesTaken)
guessesTaken += 1
if guessesTaken >= 10:
break
...
答案 1 :(得分:0)
如果您也不想错过尝试,而用户只是按Enter键而不输入数字。您可以像这样在pure id
块中使用try-except
Applicative
如果用户在尝试次数保持不变的情况下意外按下Enter键,则将允许用户继续游戏。
完整代码:
while True: