如何在Python中添加原始输入值? [英] How to add raw input values in Python?
问题描述
我正在尝试将2个原始输入值加在一起.这是代码:
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)
应该问几条腿,几条手臂,然后将它们加在一起.然后告诉 总共四肢.我在学习python的第19课中很困难,所以这就是为什么我在顶部进行"def"操作.我意识到有一种更简单的方法可以完成完全相同的事情,但是我正在尝试掌握这一特定事情的概念.
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.
当我跑步时,它说我有2条手臂,2条腿和22条肢体.如何获得增加腿部和手臂的效果,而不仅仅是将两个数字紧挨着推?
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?
现在只是在说
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? "))
示例
>>> 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
这是因为您要添加strings
,而当您执行string+string
时,它只是将两个字符串连接在一起.这是因为raw_input
的默认类型是str
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
这篇关于如何在Python中添加原始输入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!