python怎么输入值_如何在Python中添加原始输入值?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值