艰难地通过Python并尝试即兴编写cod

2024-05-06 08:43:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在练习21“艰难地学习Python”。在

以下是原始代码:

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)


# A puzzle for the extra credit, type it in anyway.
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?"

现在,我正试图通过创建一个新函数并返回使代码成为我自己的代码。在

这就是我要做的:

^{pr2}$

我绝对没有错误。它询问有多少家餐馆和多少家杂货店,但最后就结束了。我错过什么了吗?我基本上是尝试从函数中的raw_inputprint中获取值。我肯定我漏掉了一些显而易见的东西,但我想不出来。在


Tags: 代码addagereturndefitdomultiply
1条回答
网友
1楼 · 发布于 2024-05-06 08:43:56

number_of_food = (number_restaurants, number_grocery)
通过上面的一行,您不是调用刚刚定义的函数。而是用元组覆盖它。首先,需要删除赋值运算符(=)。
即使删除了它,它也不会打印函数返回的值。您还必须添加print关键字。在

def number_of_food(restaurants, grocery):
    print "ADDING food places %r + %r" % (restaurants, grocery)
    return restaurants + grocery

number_restaurants = int(raw_input("How many restaurants are there?"))
number_grocery = int(raw_input("How many grocery stores are there?"))
total_places = number_of_food(number_restaurants, number_grocery) 
# Just remove the '=', so it will call the function
print "There are %r places for food."%total_places 
#This will print the returned value

相关问题 更多 >