I'm trying to get 2 raw input values added together. Here's the code:
def number_of_limbs(legs, arms, limbs):
print "You have %s legs O.o" % legs
print "You also have %s arms o.O" % arms
print "You have %r limbs!! O.O" % limbs
legs = int(raw_input("How many legs do you have? "))
arms = int(raw_input("And how many arms do you have? ")
limbs = legs + arms
number_of_limbs(legs, arms, limbs)
It's supposed to ask how many legs, how many arms, and then add them together. Then tell how
many limbs in total. I'm in lesson 19 of learn python the hard way so that's why i'm doing the "def" thing at the top. I realize there's easier ways to do the exact same thing but i'm trying to grasp the concept of this particular thing.
When I run it, it says I have 2 arms, 2 legs, and 22 limbs. How do I get it to add legs and arms and not just push the two numbers next to each other?
Now it's just saying
File "ex1.py", line 8
limb = legs + arms
^
SyntaxError: invalid syntax
解决方案
You have to cast them as ints:
legs = int(raw_input("How many legs do you have? "))
arms = int(raw_input("And how many arms do you have? "))
Example
>>> number_of_limbs(legs, arms, limbs)
You have 2 legs O.o
You also have 2 arms o.O
You have 4 limbs!! O.O
This is because you are adding strings and when you do string+string it simply concatenates the two strings together. This is because the default type of raw_input is str
>>> '2'+'2'
'22'
>>> int('2')+int('2')
4