Python list index not found in load list from text file

The purpose was to force the user to enter 4 numbers, then save them in a text file, open this text file, show 4 numbers in different lines, then get the average of these numbers and display it to the user. Here is my code:

__author__ = 'Luca Sorrentino'


numbers = open("Numbers", 'r+')
numbers.truncate() #OPENS THE FILE AND DELETES THE PREVIOUS CONTENT
                    # Otherwise it prints out all the inputs into the file ever

numbers = open("Numbers", 'a')  #Opens the file so that it can be added to
liist = list() #Creates a list called liist

def entry(): #Defines a function called entry, to enable the user to enter numbers
        try:
            inputt = float(input("Please enter a number"))  #Stores the users input as a float in a variable
            liist.append(inputt) #Appends the input into liist
        except ValueError: #Error catching that loops until input is correct
            print("Please try again. Ensure your input is a valid number in numerical form")
            entry() #Runs entry function again to enable the user to retry.

x = 0
while x < 4:  # While loop so that the program collects 4 numbers
    entry()
    x = x + 1

for inputt in liist:
  numbers.write("%s\n" % inputt) #Writes liist into the text file


numbers.close() #Closes the file

numbers = open("Numbers", 'r+')

output = (numbers.readlines())

my_list = list()
my_list.append(output)

print(my_list)
print(my_list[1])

The problem is loading the numbers back from the text file and then storing each as a variable so that I can get the average of them. It seems I can’t find a way to specifically identify each number, only every byte, which is not what I want.

+4
source share
3 answers

You will have two main problems.

-, .append() , . .append(), , , ... , , . .extend() += , , .

-, , . float() .

, " ". . , float() ed .readlines():

my_list = [float(x) for x in output]

. , /, :

my_list = [float(x) for x in output if len(x.strip())]
+2

(my_list) 1 - , .

, (len (my_list)), (my_list [1]) , = 1 .

, , .

, ,

my_list = list(output)
+3

You can change the end of your program a little and it will work:

output = numbers.readlines()
# this line uses a list comprehension to make 
# a new list without new lines
output = [i.strip() for i in output]
for num in output:
    print(num)
1.0
2.0
3.0
4.0

print sum(float(i) for i in output)
10
+1
source

Source: https://habr.com/ru/post/1615315/


All Articles