Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python not summing (add) numbers, just sticking them together [duplicate]

Tags:

python

So I just started learning how to code (completely new at this) and I decided to go with Python... So I recently am learning how to use functions to do math and I was making my own "coding" to see if I can come up with the result I want which is use functions to add x + y and give me a result but I keep getting the literal x + y and not the sum of those two numbers. eg. 1 + 1 = 11 (instead of 2)

Below is the code, can anyone please tell me what I am doing wrong. Thanks!~ (and yes, I am using a book but it is somehow vague on 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'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?"
like image 731
Eric Ahn Avatar asked Oct 22 '17 17:10

Eric Ahn


2 Answers

In python (and a lot of other languages), the + operator serves a dual purpose. It can be used to get the sum of two numbers (number + number), or concatenate strings (string + string). Concatenate here means join together.

When you use raw_input, you get back the user's input in the form of a string. Thus, doing fruits + beverages invokes the latter meaning of +, which is string concatenation.

To treat the user's input as a number, simply use the built-in int() function:

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

int() here converts both strings to integers. Those numbers are then passed to add(). Keep in mind that unless you implement a check to make sure that the user has inputted a number, invalid input will cause a ValueError.

like image 62
stelioslogothetis Avatar answered Oct 27 '22 06:10

stelioslogothetis


The '+' operator can be a concatenation operator for strings, lists etc. and an addition operator for numbers. Try adding int() wrappers to your inputs. Also you may see the type of a variable via type()

like image 30
nettrino Avatar answered Oct 27 '22 06:10

nettrino