Python 不求和(添加)数字,只是将它们粘在一起

标签 python

<分区>

所以我刚开始学习如何编码(在这方面是全新的)并且我决定使用 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?"

最佳答案

在 Python(以及许多其他语言)中,+ 运算符具有双重用途。它可用于获取两个数字的总和(数字+数字),或连接字符串(字符串+字符串)。在这里连接意味着连接在一起。

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

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

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

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

关于Python 不求和(添加)数字,只是将它们粘在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46877025/

相关文章:

python - 如何将 Tkinter Canvas 坐标转换为窗口?

python - Seaborn:如何设置条形边框的线宽或颜色?

python - 时间序列分析 - 不均匀间隔的措施 - Pandas + statsmodels

python - pip install pyinstaller 没有名为 pyinstaller 的模块

python - Python中的模块导入

python - 根据另一列中的列名称处理列

python - 在 PyQt 中按下按钮时在屏幕之间移动

Python 在列表末尾限制切片负界

python - 在 PySpark 中的数据框中获取值(value)

python - 如何启用/禁用基于 QTreeView 事件的项目?