【问题标题】:ValueError in while loop inside a function函数内while循环中的ValueError
【发布时间】:2018-01-20 13:00:26
【问题描述】:

问题:

编写一个函数add_up,将用户提供的整数相加,当用户编写Stop时停止。

条件:

  • 它必须是用户输入,所以没有参数
  • 没有说明如何处理无法转换为整数的其他字符串

我的回答:

def add_up():
    string = 0
    total = 0
    while string is not "Stop":
        string = int(input())    
        total += string    
        print(total)
add_up()

【问题讨论】:

  • 您有缩进错误。请修复。
  • 你没有问问题。我们应该猜测吗?无论如何,is 不是测试相等性的方法,您的字符串将永远等于"Stop"
  • 那么这里的问题/问题是什么?
  • 好吧,如果您曾经输入过字符串“stop”,那么转换为 int 将会失败。你需要一个try/except,看看异常处理。您还需要== 而不是is not 来检查是否相等。
  • 没错!!我对如何构造它感到困惑,因为只有数字字符串可以转换为整数。有没有办法解决异常处理,因为这个问题应该在没有这些知识的情况下解决。也许是更基本的方式?在我正在学习的课程中,我还没有学习异常处理。

标签: python


【解决方案1】:

使用try/except 处理无效输入:

def add_up():
    string = 0
    total = 0
    while True:
        string = input()
        try:
            num = int(string)
            total += num
            print(total)
        except ValueError:
            if (string.lower() == "stop"):
                print("this ends now!")
                break
            else:
                print("not a number")
add_up()

如果您不想使用try/except,也可以使用if/else 语句和isidigit() 函数:

def add_up():
    string = 0
    total = 0
    while True:
        string = input()
        if (string.lower() == "stop"):
            print("this ends now!")
            break
        elif (string.isdigit()):
            num = int(string)
            total += num
            print(total)
        else:
            print("not a number")

add_up()

【讨论】:

  • 谢谢。我一直在用这个拉头发。但是我还没有了解 try/except 。有没有其他更基本的方法来解决这个问题?
猜你喜欢
  • 1970-01-01
  • 2019-07-19
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2020-03-17
  • 1970-01-01
相关资源
最近更新 更多