【问题标题】:Python 'add' function issue: why won't this work?Python“添加”功能问题:为什么这不起作用?
【发布时间】:2013-04-29 08:33:00
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

  • 非常感谢大家。因此,据我了解, a 和 b 作为字符串而不是整数返回,因此被连接而不是相加。谢谢!
  • 附带说明,add 函数已经创建! from operator import add

标签: python function add


【解决方案1】:

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.

【讨论】:

  • 没有。不是“强制转换为 int”。它不是强制转换,强制转换是告诉编译器变量包含特定类型的数据。 int() 将解析一个字符串并返回*一个整数。 “解析”或“转换”是可接受的词。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您需要将ab 转换为整数。

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

    【讨论】:

      【解决方案4】:

      这是因为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,使用+ 运算符来添加结果而不是连接它们。

      .

      【讨论】:

        【解决方案5】:

        **

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

        【讨论】:

        • 嗨,Soham,提问者的主要问题是为什么该功能不起作用。解释一下出了什么问题以及为什么您的代码会有所帮助会更有帮助。
        • 请考虑在代码中添加一点解释。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 2019-10-06
        相关资源
        最近更新 更多