Python 2:ValueError:以10为基数的int()的无效文字:'20 .0' [英] Python 2: ValueError: invalid literal for int() with base 10: '20.0'

查看:121
本文介绍了Python 2:ValueError:以10为基数的int()的无效文字:'20 .0'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个小问题.所以我有几个变量xyanswer:

I have a small problem with a math in python. So I have a few variables, x, y and answer:

>>>x = 20
>>>y = 21
>>>answer = x / y * 100
>>>answer
0

因此将其打印为空.好的,我知道它的输出为null,因为我必须打印x = 20.0而不是print x = 20.

So it's prints out null. OK i know that it's prints out null because i had to print x = 20.0 instead of print x = 20.

但是无论如何我都需要打印出来:

But anyway I need it to print out:

95.2380952381

我该怎么做?

注意:我不能只写x = 20.0吗?

我也试图这样做:

x1 = str(x) + '.0'
result = int(x1) / y * 100

但是Python给我一个错误:

But Python give me an error:

ValueError: invalid literal for int() with base 10: '20.0'

那我该如何解决呢?

推荐答案

使用from __future__ import division进行 all 个浮点除法.

或者,使用float()而不是int()来代替将字符串解释为浮点数:

Alternatively, use float() instead of int() to interpret a string as a floating point number instead:

answer = float(x) / y * 100

这篇关于Python 2:ValueError:以10为基数的int()的无效文字:'20 .0'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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