2015-10-16 113 views
0

我的代码是ValueError异常:无效的基数为10字面INT():“5.0”

# put your python code here 
a=int(input())     #a for first number 
b=int(input())     #b for second number 
op=input()      #c for operation 
if op=='+': print(a+b) 
elif op=='-': print(a-b) 
elif op=='/': 
    if b!=0: print(a/b) 
    else: print('Деление на 0!') #'Division by 0!' 
elif op=='*': print(a*b) 
elif op=='mod': print(a%b) 
elif op=='pow': print(a**b) 
elif op=='div': print(a//b) 

我的电脑做工不错,但我想学的课程,其中一个解释给我一个这样的错误:

ValueError: invalid literal for int() with base 10: '5.0' 
+0

您使用的是什么版本的Python? 'a = int(input())'并输入“5.0”将在2.7中工作,但不是3.X. – Kevin

+0

@凯文Python 3.5 – pookeeshtron

回答

3

您正在尝试将您的字符串转换为一个浮点形式表示为int。这不起作用。正如INT()的帮助下,指定:

If x is not a number or if base is given, then x must be a string, 
| bytes, or bytearray instance representing an integer literal 

请看下面的例子来帮助说明这一点:

>>> x = int("5.5") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: invalid literal for int() with base 10: '5.5' 
>>> x = float("5.5") 
>>> x 
5.5 
>>> 

改变INT浮动后运行与下面的测试输入你的代码,收益率如下:

# inputs 
5.5 
6.6 
mod 
# output 
5.5 
+0

好的。但是接下来会出现新问题: 'ZeroDivisionError:float modulo' – pookeeshtron

+1

然后当你遇到这种情况时使用'int(a)'和'int(b)'。 – KronoS

0

这是因为你试图将浮点数字符串转换为整数。由于您正在尝试创建计算器,因此请使用float()而不是int()。如果你真的只想要整数使用int(float(input()))

相关问题