【问题标题】:Python not summing (add) numbers, just sticking them together [duplicate]Python不求和(加)数字,只是将它们粘在一起[重复]
【发布时间】:2018-04-03 06:33:55
【问题描述】:

所以我刚开始学习如何编码(在这方面是全新的),我决定使用 Python ......所以我最近正在学习如何使用函数来做数学,我正在制作自己的“编码”来看看如果我能得出我想要的结果,那就是使用函数来添加 x + y 并给我一个结果,但我一直得到文字 x + y 而不是这两个数字的总和。例如。 1 + 1 = 11(而不是 2)

下面是代码,谁能告诉我我做错了什么。谢谢!~ (是的,我正在使用一本书,但它的解释有点模糊 [Learn Python the Hard Way])

def add(a, b):
    print "adding all items"
    return a + b

fruits = raw_input("Please write the number of fruits you have \n> ")
beverages = raw_input("Please write the number of beverages you have \n> ")

all_items = add(fruits, beverages)
print all_items

仅供参考,这本书给我的代码是:

    def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


 print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)

# puzzle
print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "that becomes: ", what, "Can you do it by hand?"

【问题讨论】:

  • 它应该以这种方式粘贴,因为您放入 raw_input() 的是一个字符串。检查并将其转换为整数
  • raw_input 将输入作为字符串格式发送,您需要将其类型转换为整数,即fruits = int(raw_input("Please write the number of fruits you have \n> "))
  • 快速回答的人,非常感谢它解决了我的问题,我还没有真正学会如何使用整数(我有,但它太模糊了,我没有完全理解)..cheers :)
  • 是的,您可以在 Python 中添加许多不同的东西:列表、元组、字符串、整数、浮点数,以及任何具有 __add__ 魔术方法的东西。

标签: python


【解决方案1】:

在python(和许多其他语言)中,+ 运算符有双重用途。它可用于获取两个数字的总和(数字 + 数字),或连接字符串(字符串 + 字符串)。这里的 Concatenate 表示连接在一起。

当您使用raw_input 时,您会以字符串的形式取回用户的输入。因此,fruits + beverages 调用了+ 的后一个含义,即字符串连接。

要将用户的输入视为数字,只需使用内置的int() 函数:

all_items = add(int(fruits), int(beverages))

int() 在这里将两个字符串都转换为整数。然后将这些数字传递给add()。请记住,除非您实施检查以确保用户输入了数字,否则无效输入将导致 ValueError。

【讨论】:

  • 感谢帮助我更好地理解它
  • @EricAhn 很高兴我能帮上忙。等待期结束后,请务必将答案标记为accepted,祝您好运。
  • 小问题:我想说“cast”这个词在这里是不正确的,因为您实际上想将值 convert 转换为 int 对象,而不仅仅是 投射它。 Python 语言并没有像其他一些语言那样真正进行类型转换。这里的int()“函数”其实就是int类(Python内置类型)的构造函数,是整数值的类;通过使用字符串参数调用int(),您可以将该字符串传递给int 构造函数并获得相应的int 对象。只是一个术语——否则,这个答案是完全正确的。
【解决方案2】:

“+”运算符可以是字符串、列表等的连接运算符和数字的加法运算符。尝试将 int() 包装器添加到您的输入中。你也可以通过type()看到变量的类型

【讨论】:

  • 感谢您的快速评论,这绝对有帮助
【解决方案3】:

raw_input 函数返回一个字符串,而不是一个数字。 + 运算符在用于字符串时,将它们连接起来。

您需要在结果上使用int()float() 将字符串解析为数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 2023-02-11
    • 2011-08-25
    • 2012-07-14
    • 1970-01-01
    • 2021-01-26
    相关资源
    最近更新 更多