【问题标题】:try and except is not catching error in min max function - pythontry and except 未捕获 min max 函数中的错误 - python
【发布时间】:2023-01-01 01:15:10
【问题描述】:

该程序旨在接受用户的输入,然后打印出最小值和最大值。这工作正常,直到 try and except 被测试。

代码 SN-P:

min = None
max = None
#wrap entire function in while loop
while True:
    #prompt user for input
    line = input('Enter a number: ')
    try:
        if line == 'done':
            break
        print(line)
        #min and max
        if min is None or line < min:
            min = line
            print("min:",min)
        if max is None or line > max:
            max = line
            print("max:",max)

    except:
        print('Invalid input')
        continue
#print function results
print(min,max)

当字符串值被添加为输入时,即 abcd

  • 输出为:min abc , max abc
  • 预期的输出是:“无效输入”

【问题讨论】:

  • 有效的解决方案是在最小和最大条件上方添加代码:line = int(line) 。来自用户的输入被转换成一个整数,如果它不是一个整数,那么 try 和 except 会成功执行。

标签: python-3.x try-catch


【解决方案1】:

问题是您总是将输入作为字符串进行比较。

比如用户输入“8”,然后你把字符串“8”存入min和max中。然后用户输入“abcd”,你检查“abcd”是否<“8”。这是一个完全有效的比较,因为 < 是为比较两个字符串而定义的。

如果只想比较数字,则应在进行任何比较之前将每个输入转换为数字:

min = None
max = None
#wrap entire function in while loop
while True:
    #prompt user for input
    line = input('Enter a number: ')
    try:
        if line == 'done':
            break
        print(line)
        #min and max
        line = int(line)
        if min is None or line < min:
            min = line
            print("min:",min)
        if max is None or line > max:
            max = line
            print("max:",max)

    except:
        print('Invalid input')
        continue
#print function results
print(min,max)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-14
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2011-07-30
    • 1970-01-01
    相关资源
    最近更新 更多