Jason Donegan
Jason Donegan

Reputation: 49

Python Beginner Question about practice problem

I am learning python and need help understanding what I am doing wrong. The task I am trying to accomplish is create a list of integers from 1-100, and then create two other lists based off those numbers and finish by printing both lists. However, I am having trouble with getting the second list to write to a file named target list.txt. Can someone tell me what I am doing wrong?

num1 = input("Please Input a name for the file ending it with .txt. ")
numb_list = open(num1, "w")
mylist = []


def integer_list():
    for numbers in range(1, 101):
        mylist.append(numbers)
        numb_list.write(str(numbers) + "\n")
        print(numbers, end="\n")


integer_list()
print(mylist)
numb_list.close()


def target_list():
    for numbers2 in range(25, 75):
        mylist.append(numbers2)
        target_list.write(numbers2+ "\n")
        print(numbers2, end="\n")


target_list()
print(mylist)
target_list.close()

Upvotes: 2

Views: 79

Answers (3)

flakes
flakes

Reputation: 23634

  1. You didn't open the second file. You used the name of the function target_list instead of a new file. This is what's causing your program to fail.
  2. Don't use global state in the functions. You can return a new list on each call. This prevents the one call of the function from effecting the behavior of the next call.
  3. Use function parameters to allow the function to act slightly differently. This makes the function more usable and avoids duplication of code.
def integer_list(start, end):
    file_name = input("Please Input a name for the file ending it with .txt. ")
    num_list = []
    num_file = open(file_name, "w")
    for num in range(start, end):
        num_list.append(num)
        num_file.write(str(num) + "\n")
        print(num)
    num_file.close()
    return num_list


num_list1 = integer_list(1, 101)
print(num_list1)

num_list2 = integer_list(25, 75)
print(num_list2)

Upvotes: 2

ericl16384
ericl16384

Reputation: 364

You have multiple problems with scope.

Here is the fixed code:

num1 = input("Please input a name for the file ending it with .txt ")
numb_list = open(num1, "w")

global mylist
mylist = []


def integer_list():
    for numbers in range(1, 101):
        mylist.append(numbers)
        numb_list.write(str(numbers) + "\n")
        print(numbers)#, end="\n")


integer_list()
print(mylist)
#numb_list.close()


def target_list():
    for numbers in range(25, 75):
        mylist.append(numbers)
        numb_list.write(str(numbers)+"\n") # Needed to be a string
        print(numbers)#, end="\n")


target_list()
print(mylist)
numb_list.close()

Upvotes: 0

Michael
Michael

Reputation: 1

You did not open a second file. target_list.write is where you are having an error and the reason is because target_list is a function not a file.

Upvotes: 0

Related Questions