4

The assignment was to get a user to input 4 numbers, then store them in a text file, open that text file, show the 4 numbers on different lines, then get the average of those numbers and display it to the user. Here is my code so far:

__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 one as a variable so that I can get the average of them. I can't seem to find a way to specifically locate each number, just each byte which is not what I want.

5
  • 1
    take out the brackets around your readlines functions and just try print(output): you should see a list of your numbers. Commented Nov 10, 2015 at 21:36
  • Aside from the incorrect output with print(my_list) and the crash at print(my_list[1]), there are some other issues with this code. Once you get it working, I encourage you to ask a question on Code Review. Commented Nov 10, 2015 at 21:59
  • 1
    Off-topic: Your file management is really poor. You open the file once with "r+" just to truncate (not actually reading), then (without closing) re-open for append, then later reopen for "r+" (this time reading, but not writing, so the + was pointless). Just open it once for "w+", which will let you both read and write, and truncates the file for you. When you finish writing (to populate the file), you can seek back to the beginning to read it. You could also switch to a with statement to manage the file object lifetime. Commented Nov 10, 2015 at 22:11
  • @ShadowRanger Hi, Thanks for this. I have replaced all the opening in different formats with 'w' and it works apart from the fact I'm unsure about how you get it to seek back to the beginning? Thanks, Commented Nov 11, 2015 at 12:57
  • @lucafsorrentino: Since you're both reading and writing (but want to truncate), you'd use mode w+. API for seeking is documented in the io module. Commented Nov 11, 2015 at 18:06

3 Answers 3

3

Your list (my_list) has only 1 item - a list with the items you want.

You can see this if you try print(len(my_list)), so your print(my_list[1]) is out of range because the item with index = 1 does not exist.

When you create an empty list and append output, you are adding one item to the list, which is what the variable output holds for a value.

To get what you want just do

my_list = list(output)
Sign up to request clarification or add additional context in comments.

Comments

2

You'll have two main problems.

First, .append() is for adding an individual item to a list, not for adding one list to another. Because you used .append() you've ended up with a list containing one item, and that item is itself a list... not what you want, and the explanation for your error message. For concatenating one list to another .extend() or += would work, but you should ask yourself whether that is even necessary in your case.

Second, your list elements are strings and you want to work with them as numbers. float() will convert them for you.

In general, you should investigate the concept of "list comprehensions". They make operations like this very convenient. The following example creates a new list whose members are the respectively float()ed versions of your .readlines() output:

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

The ability to add conditionals into a list comprehension is also a real complexity-saver. For example, if you wanted to skip any blank/whitespace lines that had crept into your file:

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.