如何修改代码可以将平均价格打印到文件?

如何修改代码可以将平均价格打印到文件?

def average_price(prices):
  """
  Calculates the average price of a list of prices.

  Args:
    prices: A list of prices.

  Returns:
    The average price.
  """

  # Calculate the average price.
  average_price = sum(prices) / len(prices)

  return average_price


# Print the average price to the console.
print(average_price(prices))

To print the average price to a file, you can modify the code as follows:

def average_price(prices):
  """
  Calculates the average price of a list of prices.

  Args:
    prices: A list of prices.

  Returns:
    The average price.
  """

  # Calculate the average price.
  average_price = sum(prices) / len(prices)

  # Print the average price to a file.
  with open('average_price.txt', 'w') as file:
    file.write(str(average_price))

  return average_price


# Print the average price to the console.
print(average_price(prices))

Note:

  • You will need to create a file named average_price.txt in the same directory as your script.
  • The file will contain a single floating-point number, representing the average price.
  • The file will be opened in write mode ('w'), so any existing contents will be overwritten.
相似内容
更多>