我如何允许我的尝试块多次工作?

发布于 2025-02-12 00:40:50 字数 666 浏览 0 评论 0原文

因此,我在上课时一直在尝试进行循环,但是我发现修复错误曾经有效。这是我的代码:

class team:
    def __init__(self,budget):
        self.budget = budget      

def test_func():
    team.budget = input("How much money should your baseball team own? ")
    try:
        team.budget = int(team.budget)
    except ValueError:
        print("Either you added a dollar sign, put in text or tried something weird. Either way, don't do that.")
        team.budget = input("How much money should your baseball team own? ")

test_func()

此尝试块应阻止任何不是整数的东西,但是这是我两次导致错误时发生的事情:

。用户进入可以接受的东西?

非常感谢!

So I've been trying to do a loop when working with classes but I find that fixing errors work once. Here's my code:

class team:
    def __init__(self,budget):
        self.budget = budget      

def test_func():
    team.budget = input("How much money should your baseball team own? ")
    try:
        team.budget = int(team.budget)
    except ValueError:
        print("Either you added a dollar sign, put in text or tried something weird. Either way, don't do that.")
        team.budget = input("How much money should your baseball team own? ")

test_func()

This try block should block anything that's not an integer, but here's what happens when I cause an error twice:

After adding user input.

Is there something you'd recommend to allow the input to happen until the user enters in something acceptable?

Much thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

绅士风度i 2025-02-19 00:40:50

您需要使用循环重复提示,直到输入有效的整数为止。

def test_func():
    while True:
        team.budget = input("How much money should your baseball team own? ")
        try:
            team.budget = int(team.budget)

            break  # Stop the loop since the input is valid.
        except ValueError:
            print("Either you added a dollar sign, put in text or tried something weird. Either way, don't do that.")

You need to use a loop to repeat the prompt until a valid integer is entered.

def test_func():
    while True:
        team.budget = input("How much money should your baseball team own? ")
        try:
            team.budget = int(team.budget)

            break  # Stop the loop since the input is valid.
        except ValueError:
            print("Either you added a dollar sign, put in text or tried something weird. Either way, don't do that.")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文