【问题标题】:Python 3.1 Problems with "Else:" in my codePython 3.1 在我的代码中出现“Else:”问题
【发布时间】:2016-03-21 16:24:22
【问题描述】:

您好我是编码新手,这里我根据用户的输入编写了一个简单的代码。我可以得到每个 if 和 elif 响应,但是当输入不是整数时,我的程序会失败。

def tables_bussed():
    tables = input("How many tables can you bus per hour? (I can only read numbers.)")
    if int(tables) > 80:
        print ("That\'s rediculous, you lying twit.")
        tables_bussed()
    elif int(tables) > 60:
        print ("If what you are saying is true then you have quite a talent!")
    elif int(tables) > 30:
        print ("Impressive! Yet there\'s always room for improvement, now isn\'t there.")
    elif int(tables) > 0:
        print ("How sad.")
    else:
        print ("Are you dumb or just daft.")
        tables_bussed()

tables_bussed()

我的 else 子句中是否遗漏了什么?

【问题讨论】:

  • 您得到的确切错误是什么?您的最终打印没有缩进,但我认为这只是复制粘贴问题?
  • 缺少缩进
  • else 语句中的缩进似乎不正确。
  • 错误信息的最后一行是 ValueError: invalid literal for int() with base 10: ''
  • 请编辑您的缩进以与您的代码完全匹配。我认为这对Python 语言很重要

标签: python


【解决方案1】:

你需要一个try except子句,我不想​​重做你的程序,但这里是一般概念

def tables_bussed():
    tables = input("How many tables can you bus per hour? (I can only read numbers.)")
    try:
        tables = int(tables)
    except ValueError:
        print ('Sorry dude, you must input a number that is an integer')
        tables_bussed()

因为我在 try 子句中将表定义为整数,所以您不必重复使用 int(tables) 语句,您只需测试值即可

所以在你定义表格之后放(注意你有一些缩进问题,但可能不在你的代码中)

程序会尝试将表格解析为整数,如果不成功会提示用户重试

关于 try except 子句有很多,它们对于捕捉用户输入问题或您可能遇到的其他问题非常有用

【讨论】:

  • 好的,谢谢,我会检查这是否有效!永远不要尝试子句,这是我自学的第三天,哈哈
  • 虽然这有效,但它实际上是递归的,在这种情况下,while循环是一个更好的选择
  • 您为什么不在答案中解释为什么您认为它更好,而不是在我的答案下方发表评论。断言对新程序员来说不是很有用。你应该清楚地说明情况。你有一个例子,我一般不喜欢 while 循环,所以如果你帮助他们了解发生了什么,用户将获得最大的好处。
  • @PyNEwbie 答案已经被接受,我只是想展示一个替代方案,但是既然你问我觉得不必要的递归比简单的循环更糟糕 - 你“不喜欢 while 循环”的事实似乎也是一个奇怪的断言。在这种情况下,while 循环提供了一种明确的方法来强制输入正确,而不会由于递归而导致堆栈溢出。
  • 我只是说另一个答案通常对我们新手没有帮助,除非他们解释了为什么它更好,更有效。等等。我不是受过培训的程序员,所以这只是对我的一个断言,这是更好的..对于 SO 的答案要生存时间,他们应该有一个解释,而不仅仅是代码转储。我的解释不详细“尝试将表解析为整数,如果不成功,它将提示用户重试”当我查看您的代码时,我想知道它在开始时是否为真 - 为什么它不能在开始?
【解决方案2】:

把它全部放在一个while循环中:

def tables_bussed():
    while True:
        tables = input("How many tables can you bus per hour? (I can only read numbers.)")
        if tables.isdigit():
            if int(tables) > 80:
                print ("That\'s rediculous, you lying twit.")
                continue
            elif int(tables) > 60:
                print ("If what you are saying is true then you have quite a talent!")
            elif int(tables) > 30:
                print ("Impressive! Yet there\'s always room for improvement, now isn\'t there.")
            elif int(tables) > 0:
                print ("How sad.")
            break
        else:
            print ("Are you dumb or just daft.")

tables_bussed()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2019-01-08
    • 2019-09-11
    相关资源
    最近更新 更多