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

时间:2015-11-11 09:51:31

标签: python text input numbers average

我需要让用户输入一定数量的数字(5)并将它们存储在文本文件中。 我还需要找到这些数字的平均值。我会使用sum函数然后除以5吗?

这是for python,我在OS X上使用IDLE 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()

1 个答案:

答案 0 :(得分:0)

我摆弄了一下,而不是将列表存储为文本文件,我决定将其保存在列表中。以下是我最后提出的建议:

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)