如何在输入整数而不是字符串时添加错误消息

发布于 2025-01-14 18:37:03 字数 682 浏览 1 评论 0原文

我试图在输入字符串而不是整数时添加错误。我看过其他类似的帖子,但是当我尝试将其实现到我的代码中时,它不断吐出错误。我这里有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

愛上了 2025-01-21 18:37:03

请注意,您要求三次输入完全相同的输入。实际上没有必要,也根本不需要两个循环。只需将 guess 设置为永远不等于数字的默认值 (None) 并使用一个 input,用 包裹>尝试/除外

import random

number = random.randrange(1, 50)
guess = None  

while guess != number:
    try:
        guess = int(input("Guess a number between 1 and 50: "))
    except ValueError:
        print("Please input a number.")
    else:
        if guess < number:
            print("You need to guess higher. Try again.")
        elif guess > number:
            print("You need to guess lower. Try again.")

print("You guessed the number correctly!")

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 single input, wrapped with try/except:

import random

number = random.randrange(1, 50)
guess = None  

while guess != number:
    try:
        guess = int(input("Guess a number between 1 and 50: "))
    except ValueError:
        print("Please input a number.")
    else:
        if guess < number:
            print("You need to guess higher. Try again.")
        elif guess > number:
            print("You need to guess lower. Try again.")

print("You guessed the number correctly!")
爱格式化 2025-01-21 18:37:03

您可以尝试为输入语句运行 while 循环。检查输入(字符串格式)是否为数字,然后将其转换为 int。
示例代码:

a = input()
while not a.isnumeric():
    a = input('Enter a valid integer')
a = int(a)

代码一直执行,直到 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:

a = input()
while not a.isnumeric():
    a = input('Enter a valid integer')
a = int(a)

The code executes until the value of a is an int

时光是把杀猪刀 2025-01-21 18:37:03

您的代码不起作用,因为缩进不正确

import random

number = random.randrange(1, 50)
while True:
    try:
        guess = int ( input("Guess a number between 1 and 50: ") ) # here
        break # here
    except ValueError: # here
        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!")

输出

Guess a number between 1 and 50: aa
Please input a number.
Guess a number between 1 and 50: 4
You need to guess higher. Try again.

your code did not work because the indentation is not right

import random

number = random.randrange(1, 50)
while True:
    try:
        guess = int ( input("Guess a number between 1 and 50: ") ) # here
        break # here
    except ValueError: # here
        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!")

Output

Guess a number between 1 and 50: aa
Please input a number.
Guess a number between 1 and 50: 4
You need to guess higher. Try again.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文