如何在输入整数而不是字符串时添加错误消息
我试图在输入字符串而不是整数时添加错误。我看过其他类似的帖子,但是当我尝试将其实现到我的代码中时,它不断吐出错误。我这里有一个 1 到 50 之间的猜数字游戏。我一生都无法弄清楚出了什么问题。
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") )
break
except ValueError:
print("Please input a number.")**
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
I am trying to add an error when a string is entered instead of an integer. I've looked at other similar posts but when I try and implement it into my code it keeps spitting errors out. I have a number guessing game between 1 and 50 here. Can't for the life of me figure out what's wrong.
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") )
break
except ValueError:
print("Please input a number.")**
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,您要求三次输入完全相同的输入。实际上没有必要,也根本不需要两个循环。只需将
guess
设置为永远不等于数字的默认值 (None
) 并使用一个input
,用包裹>尝试/除外
:Note that you're asking three times for the exact same input. There is really no need for that and no need for two loops at all. Just set the
guess
to a default value that will never be equal to the number (None
) and use one singleinput
, wrapped withtry/except
:您可以尝试为输入语句运行 while 循环。检查输入(字符串格式)是否为数字,然后将其转换为 int。
示例代码:
代码一直执行,直到
a
的值为int
You could try running a while loop for the input statements. Checking if the input(in string format) is numeric and then casting it to int.
Sample code:
The code executes until the value of
a
is anint
您的代码不起作用,因为缩进不正确
输出
your code did not work because the indentation is not right
Output