[英]How to add a user defined function by itself on python?
I'm not sure if it's possible or I misread the instruction for my homework but here's what I mean 我不确定是否可以,或者我误读了作业说明,但这就是我的意思
def price():
input("Please enter price of product: ")
price()
price()
price()
def tot():
#find the sum of the 3 values
tot()
So I called out the function price() three times to allow the use to enter 3 values. 因此,我三次调用了price()函数,以允许用户输入3个值。 I would like to add up these 3 values in the function tot() but how can I do that when they have no labels?
我想将这3个值加到函数tot()中,但是当它们没有标签时该怎么办呢? Do the parameters play a part here?
参数在这里起作用吗? It's an introductory course so I know very little and it was not explained.
这是一门入门课程,所以我了解的很少,也没有解释。 Here is the full question and how the output should be.
这是完整的问题以及输出应如何。 As you can see it says call function 3 times
如您所见,它说调用函数3次
Image of assignment : 作业图片 :
You need to store the user input somewhere so you can use it later. 您需要将用户输入存储在某个地方,以便以后使用。 A simple way to do this is to store input values in a list.
一种简单的方法是将输入值存储在列表中。
Here's an example: 这是一个例子:
def get_price():
raw_input = input("Please enter price of product: ")
return int(raw_input)
def get_total(prices):
# sum them up
def run():
prices = []
for _ in range(3): # three times
new_price = get_price()
prices.append(new_price)
total_price = get_total()
print(f"Total is ${total_price}")
Alternatively, (if you don't care about the individual prices after they've been entered) you could just keep a running total and add to it each time a user inputs a new price. 或者,(如果您不关心输入单个价格之后的价格),则可以保持运行总计并在每次用户输入新价格时将其添加到其中。 The point is that you need to do something with the user input.
关键是您需要对用户输入进行某些操作。
Functions can return
a value. 函数可以
return
一个值。 So if I define a function: 因此,如果我定义一个函数:
def getCheese():
return "blue"
The output from that function (the part return
acts on) can be assigned where the function is called: 可以在调用该函数的位置分配该函数的输出(
return
零件起作用的部分):
my_cheese = getCheese()
print( my_cheese ) # prints "blue"
So for your question, you need to assign the returned result from python's built-in input()
function, and then return that from your price()
function. 因此,对于您的问题,您需要从python的内置
input()
函数分配返回的结果,然后从price()
函数返回该结果。 These returned values can then be stored in some other variables to tally up the prices. 然后,可以将这些返回值存储在其他一些变量中,以计算价格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.