【发布时间】: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