Python'添加'功能问题:为什么这不起作用?

时间:2013-04-29 08:33:00

标签: python function add

我刚刚开始学习Python,我是一个绝对的新手。

我开始学习函数了,我写了这个简单的脚本:

def add(a,b):   
    return a + b

print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")

result = add(a, b)

print "The result is: %r." % result 

脚本运行正常,但结果不是总和。即:如果我为'a'输入5,为'b'输入6,结果将不是'11',而是56.如下:

The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: '56'.

任何帮助都将不胜感激。

5 个答案:

答案 0 :(得分:6)

raw_input返回字符串,您需要将其转换为int

def add(a,b):   
    return a + b

print "The first number you want to add?"
a = int(raw_input("First no: "))
print "What's the second number you want to add?"
b = int(raw_input("Second no: "))

result = add(a, b)

print "The result is: %r." % result 

输出:

The first number you want to add?

First no: 5
What's the second number you want to add?

Second no: 6
The result is: 11.

答案 1 :(得分:1)

您需要将字符串转换为int以添加它们,否则+将只执行字符串连接,因为raw_input返回 raw 输入(字符串):

result = add(int(a), int(b))

答案 2 :(得分:0)

这是因为raw_input()返回一个字符串,并且+运算符已被重载,以便字符串执行字符串连接。尝试。

def add(a,b):   
    return int(a) + int(b)

print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")

result = add(a, b)

print "The result is: %r." % result

结果输出如下。

>>> 
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: 11

将字符串输入转换为int,使用+运算符添加结果而不是连接它们。

答案 3 :(得分:0)

您需要将ab转换为整数。

def add(a, b):
    return int(a) + int(b)

答案 4 :(得分:-1)

<块引用>

**

**>raw_input 总是返回字符串。您需要将字符串转换为int/float数据类型进行添加,否则添加将执行字符串连接。

您可以自己检查变量的类型:print(type(a), type(b))

只需调整您的功能**

**

def add(a, b):
    return int(a) + int(b)

def add(a, b):
    return float(a) + float(b)