Python“添加”函数问题:为什么这不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16274318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:11:09  来源:igfitidea点击:

Python 'add' function issue: why won't this work?

pythonfunctionadd

提问by user2331291

I've just started studying Python, and I'm an absolute newbie.

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

I'm starting to learn about functions, and I wrote this simple script:

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

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 

The script runs OK, but the result won't be a sum. I.e: if I enter 5 for 'a', and 6 for 'b', the result will not be '11', but 56. As in:

脚本运行正常,但结果不会是总和。即:如果我为 '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'.

Any help would be appreciated.

任何帮助,将不胜感激。

采纳答案by Kiro

raw_inputreturns string, you need to convert it to int

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 

Output:

输出:

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.

回答by jamylak

You need to convert the strings to ints to add them, otherwise +will just perform string concatenation since raw_inputreturns rawinput (a string):

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

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

回答by Sukrit Kalra

This is because raw_input()returns a string and +operator has been overloaded for strings to perform string concatenation. Try.

这是因为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 resultant output is as follows.

结果输出如下。

>>> 
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

Converting the string inputs to int, uses the +operator to add the results instead of concatenating them.

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

.

.

回答by Jordan Jambazov

You need to cast aand bto integer.

你需要投ab到整数。

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