为什么以下内容会评估为python中的ValueError? [英] Why does the following evaluate to a ValueError in python?

查看:71
本文介绍了为什么以下内容会评估为python中的ValueError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前一段时间我们在编码,遇到一个小问题.我们想尝试将浮点数转换为整数

We were coding something awhile ago and we came across a small problem. We wanted to try to convert float numbers to integers

这是代码:

x = int(input(())
print x

我们尝试了代码,然后输入5.5.评估为 ValueError .从逻辑上讲,这在逻辑上是合理的.但是,如果我们尝试以下代码:

We tried the code and put 5.5. It evaluated to a ValueError. Logically, it is sound in logic. But if we try the following code:

x = int(float(input((()))) x = int(5.5),其计算结果为5.

x = int(float(input(())) OR x = int(5.5), it evaluates to a value of 5.

为什么会这样?

推荐答案

在第一种情况下,您正在调用int("5.5"),因为input()返回一个字符串.那是一个ValueError,因为5.5不是int,而python的设计人员决定不进行任何隐式转换.

In the first case, you are calling int("5.5"), because input() returns a string. that's a ValueError because 5.5 is not an int, and the designers of python decided not to do any implicit casting.

在第二种情况下,您需要调用float("5.5")(它是5.5,因为可以将"5.5"转换为您所要求的float),然后调用int(5.5),这是转换float的结果转换为int(python为此使用截断;如果不是您想要的,则可以调用round()代替.)

In the second case, you care calling float("5.5"), which is 5.5 because "5.5" can be converted to a float as you asked, and then int(5.5), which is the result of converting a float to an int (python uses truncation for this; you can call round() instead if that's not what you want).

第三种情况与第二种情况的第二步相同.

The third case is just the same as the second step of the second case.

这篇关于为什么以下内容会评估为python中的ValueError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆