如何要求用户输入数字,然后存储在文本文件中?

2024-10-02 00:37:41 发布

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

我需要让用户输入一定数量的数字(5),并将它们存储在一个文本文件中。 我还需要找出这些数字的平均值。我会用求和函数除以5吗?你知道吗

这是针对python的,我在osx上使用空闲的3.4版本

lst = list() #creates a list to later store nubers in

def addtolist():  #creates a function for adding numbers to the list
  def listcount():  #
        try:
              lst.append(int(input("Enter a number:")))
        except ValueError:
              print("That was not a number")
        print(lst)
  listcount()

  yes = ["yes", "y"]
  no = ["no", "n"]
  yup = ["yes", "y"]
  nah = ["no", "n"]

  enteragain = input("Enter another number? yes/no")
  if enteragain in yes:
        print("Ok")
  elif enteragain in no:
        print("We'll try again")
        addtolist()

  runagain = input("Are those the numbers you wanted to enter?")
  if runagain in yes:
        print("Ok")
  elif runagain in no:
        print("We'll try again")
        addtolist()

addtolist()

Tags: tonoinnumberinput数字listyes
1条回答
网友
1楼 · 发布于 2024-10-02 00:37:41

我对它做了一点修改,并没有将列表存储为文本文件,而是决定以列表的形式保存它。下面是我在最后得出的结论:

lst = list()
def addtolist():  #creates a function for adding numbers to the list
  def listcount():  #
        try:
              lst.append(int(input("Enter a number: ")))
        except ValueError:
              print("That was not a number")
              addtolist()
        print(lst)
  listcount()

  yes = ["yes", "y"]
  no = ["no", "n"]

  def playagain():
        enteragain = input("Enter another number? yes/no?... ")
        if enteragain in no:
              print("Ok!\n Calculating average.../n")
        elif enteragain in yes:
              print("Ok then!")
              addtolist()
        else:
              print("Please type either yes or no")
              playagain()
  playagain()

addtolist()

total = sum(lst)
numbers = len(lst)
average = total/numbers

print("The average of", lst, "is", average)

相关问题 更多 >

    热门问题