Python doesn't sum (add) numbers, just sticking them together

So, I just started learning how to code (brand new in this), and I decided to go with Python ... So I recently learn how to use functions for mathematics, and I did my own β€œencoding” to see if I can come up with the result, I want to use the functions to add x + y and give me the result, but I keep getting the literal x + y, not the sum of these two numbers. eg. 1 + 1 = 11 (instead of 2)

Below is the code, can someone tell me what I am doing wrong. Thank! ~ (and yes, I use the book, but it is somehow vague in the explanations [Learn Python the Hard Way])

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

FYI, the code the book gave me was:

    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 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?"
+4
source share
3 answers

python ( ) + . ( + ) ( + ). .

raw_input, . , fruits + beverages +, .

, int():

all_items = add(int(fruits), int(beverages))

int() . add(). , , , , ValueError.

+10

"+" , .. . int() wrappers . type()

+2

The function raw_inputreturns a string, not a number. The operator +used in strings combines them.

You need to parse strings in numbers, using int()or float()as a result.

+2
source

Source: https://habr.com/ru/post/1687983/


All Articles