How to add raw input values in Python?

旧时模样 提交于 2020-01-30 08:09:48

问题


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

回答1:


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



回答2:


Convert them to integers:

legs = int(raw_input("How many legs do you have? "))
arms = int(raw_input("And how many arms do you have? "))

At the moment they are strings, this is the default datatype from raw_input.

>>> example = raw_input()
2
>>> type(example)
<class 'str'>

When you add two strings together (right there you have '2' and '2'), Python just concatenates them into one single string. (So in that case it will result in '22')

>>> '2' + '2'
'22'

It should now give the correct result.

A minimal example of what the fixed version does:

>>> legs = int(raw_input())
2
>>> arms = int(raw_input())
2
>>> limbs = legs + arms
>>> limbs
4

You can now pass that to the function without trouble.



来源:https://stackoverflow.com/questions/23044232/how-to-add-raw-input-values-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!