python - 为什么我的try-exception-final无法正常工作

标签 python error-handling

这是来自udemy的作业,我的解决方案无法正常工作,这是一个问题:
编写一个函数,要求一个整数并打印其平方。尝试使用while循环,但else块可解决输入错误的问题。
这是我的解决方案:

def ask():
    while True:
        try:
            user_input = int(input('give me int energe:'))
            squ = user_input**2
            print('boom! show you my power:'+squ)
        except:
            print('lack of int energe')
            continue
        else:
            print('Gotcha')
            break
        finally:
            print('boooooom')
        
    pass
如果我输入了str,则异常运行良好,但是即使我输入了int,也显示出与str相同的结果,为什么会这样?
my error screenshot
这是正确的解决方案:
def ask():
    
    while True:
        try:
            n = int(input('Input an integer: '))
        except:
            print('An error occurred! Please try again!')
            continue
        else:
            break
            
        
    print('Thank you, your number squared is: ',n**2)
我不确定为什么我的尝试不能顺利进行

最佳答案

您的print语句引发异常。您不能使用+附加字符串和整数。无论使用

print('boom! show you my power:' + str(squ))
要么
print('boom! show you my power:', squ)
通常,除语句外,无类型是一个非常糟糕的主意。如果您改为编写except ValueError:,而仅捕获通过尝试使用int()函数将字符串转换为int引发的错误,您将立即发现问题。

关于python - 为什么我的try-exception-final无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64191208/

相关文章:

python - 如何使用 Boto3 Python 在 S3 中创建 zipfile?

python:如何在没有互联网连接的情况下创建 virtualenv

php - 我应该一直进行MySQL错误检查吗?

php - PHP查看密码是否匹配,如果匹配,则提交其数据

asp.net - IIS 7错误代码

python - 对于在 python 中使用 `with` 关键字的类,我可以让它 __repr__ (打印)本身吗?

python - 识别另一个 pandas DataFrame 的 View 或副本

ios - stripe iOS 集成中的creditCard.validateCardReturningError(&error)

r - 导入GeoTiff文件时出错-R RASTER软件包

python - Unicode 大小写转换