3

我刚刚开始学习 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'.

任何帮助,将不胜感激。

4

5 回答 5

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.
于 2013-04-29T08:34:32.563 回答
1

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

result = add(int(a), int(b))
于 2013-04-29T08:33:57.127 回答
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, 使用+运算符来添加结果而不是连接它们。

.

于 2013-04-29T08:35:22.007 回答
0

您需要将ab转换为整数。

def add(a, b):
    return int(a) + int(b)
于 2013-04-29T08:35:55.597 回答
-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)
于 2021-07-22T21:49:09.483 回答