Python没有总结(添加)数字,只是将它们粘在一起

Eri*_*Ahn 4 python

所以我刚开始学习如何编码(全新的),我决定使用Python ...所以我最近学习如何使用函数来做数学,我正在制作自己的"编码",看看我是否可以得出我想要的结果是使用函数来添加x + y并给我一个结果但是我一直得到文字x + y而不是这两个数字的总和.例如.1 + 1 = 11(而不是2)

以下是代码,任何人都可以告诉我我做错了什么.谢谢!〜(是的,我正在使用一本书,但它在解释方面有点模糊[学习Python的艰难之路])

def add(a, b):
    print "adding all items"
    return a + b

fruits = raw_input("Please write the number of fruits you have \n> ")
beverages = raw_input("Please write the number of beverages you have \n> ")

all_items = add(fruits, beverages)
print all_items
Run Code Online (Sandbox Code Playgroud)

仅供参考,本书给我的代码是:

    def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


 print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)

# puzzle
print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "that becomes: ", what, "Can you do it by hand?"
Run Code Online (Sandbox Code Playgroud)

sty*_*ybl 10

在python(以及许多其他语言)中,+运算符有双重用途.它可用于获取两个数字(数字+数字)的总和,或连接字符串(字符串+字符串).这里的连接意味着连接在一起.

使用时raw_input,您将以字符串的形式返回用户的输入.因此,fruits + beverages调用后者的意思+,即字符串连接.

要将用户的输入视为数字,只需使用内置int()函数:

all_items = add(int(fruits), int(beverages))
Run Code Online (Sandbox Code Playgroud)

int()这里将两个字符串转换为整数.然后将这些数字传递给add().请记住,除非您执行检查以确保用户输入了数字,否则无效输入将导致ValueError.