我该如何解决“值错误”:我不断收到无效的文字错误

时间:2020-09-22 17:03:10

标签: python python-3.x

我不断收到错误消息

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

对于以下代码:

def calculator():
    print('Input first number')
    n = input()
    
    print('Input second number')
    u = int(input())
    
    print('Input add, minus, multi, divide')
    s = int(input())
    
    add = (n + u)
    minus = (n - u)
    multi = ( n * u)
    divide = (n / u)
    
    if s == add:
        print(add)
        
calculator()

有人可以帮我吗?

4 个答案:

答案 0 :(得分:0)

这看起来不正确

print('Input add, minus, multi, divide')
s = int(input())

我假设您只想要一个字符串,而不是整数?

s = input()

然后再进行字符串比较

if s == 'add':
    print(add)

类似地,您的第一个输入未转换为int,因此您以后的算术将出现问题。

答案 1 :(得分:0)

首先,由于数字是int,因此必须用int(input())表示这一点

此后,当您要获得的动作包含字符时,只能输入()

由于输入的操作数值将包含字符,因此str是一个值,因此在与if相等时必须使用“ add”。

def calculator():
    print('Input first number')
    n = int(input())

    print('Input second number')
    u = int(input())

    print('Input add, minus, multi, divide')
    s = input()

    add = (n + u)
    minus = (n - u)
    multi = ( n * u)
    divide = (n / u)

    if s == "add":
        print(add)
    
calculator()

答案 2 :(得分:0)

我认为这就是您想要做的。

def calculator():
    n = int(input('Input first number'))
    #   ^^^
    # First make sure the numbers you are inputting are being changed to integers

    u = int(input('Input second number'))

    # Then this should be kept a string
    s = input('Input add, minus, multi, divide')
    
    add = (n + u)
    minus = (n - u)
    multi = ( n * u)
    divide = (n / u)
    
    # You want to compare the variable s to a string add. Not the variable add
    if s == 'add':
        print(add)
        
calculator()```

答案 3 :(得分:0)

这将是可行的:

def calculator():
    print('Input first number')
    n = int(input())

    print('Input second number')
    u = int(input()) #has to be an integer

    print('Input add, minus, multi, divide')
    s = input() # you can't cast a string of letters to integer

    add = n + u
    minus = n - u
    multi = n * u
    divide = (n / u)

    if s == 'add': #you should be comparing a string to s and not a variable
       print (add)
    
calculator()