简体   繁体   English

对变量使用round()时出错

[英]Error when using round() for a variable

I never coded before and started with Python-3.5 a few days ago. 我从没写过代码,几天前开始使用Python-3.5。 After some exercise i try to play around myself. 经过一些运动后,我尝试在自己周围玩耍。 Last time I wanted to create a script which stores the input as a variable and rounds it to three decimals. 上一次我想创建一个脚本,将输入存储为变量并将其四舍五入到小数点后三位。 Unfortunately I get an error when I try to do that: 不幸的是,当我尝试这样做时出现错误:

round (spam, 3)
TypeError: type str doesn't define __round__ method"

I tried to look this up in the Q&A but you guys seem to have more complex problems related to this error msg. 我试图在“问答”中查找此消息,但你们似乎遇到了与此错误消息有关的更复杂的问题。

So this is what I entered in the file editor when I got the error msg: 所以这是我收到错误消息时在文件编辑器中输入的内容:

print('Pls enter value')
spam = input()
#print(spam)
round(spam, 3)

when I enter the following in the interactive shell the rounding seems to work though: 当我在交互式外壳中输入以下内容时,四舍五入似乎有效:

>>> spam = 3.666666
>>> round (spam, 3)
3.667

So why is the same logic working in the shell but not in the File editor ? 那么,为什么相同的逻辑在外壳程序中起作用而在文件编辑器中却不起作用? Thanks in advance! 提前致谢!

The difference is that in the second case you supply the value of spam using a float literal (that is, spam = 3.666666 ) while, in the first case you get it from calling input() which isn't exactly the same. 区别在于,在第二种情况下,您使用浮点文字提供spam的值(即spam = 3.666666 ),而在第一种情况下,您是通过调用input()来获取spam = 3.666666而这并不完全相同。

The function input() returns a str instance in Python 3 and, for str types, the round function doesn't make much sense; 函数input()在Python 3中返回一个str实例,对于str类型, round函数没有多大意义; you need to explicitly transform it to a float by wrapping the result of input() with float() : 您需要通过使用float()包装input()的结果来将其显式转换为float:

spam = float(input())  # change input to 'float' type

Now, you can call round on it. 现在,您可以对此进行round You do need to be careful that the input you actually supply is indeed transformable to a float or else a ValueError will be raised. 确实需要注意,您实际提供的输入确实可以转换为float ,否则将引发ValueError

In addition to that, no need to add the print call before input , input has a prompt argument that allows you to specify text before submitting input: 除此之外,无需在input之前添加print调用, input具有prompt参数,可让您在提交输入之前指定文本:

spam = input("Enter valid float number: ") 

You should now get similar results for both cases. 对于这两种情况,您现在都应该获得相似的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM