[英]Python Beginner Question about practice problem
I am learning python and need help understanding what I am doing wrong.我正在学习 python,需要帮助理解我做错了什么。 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.
我试图完成的任务是创建一个从 1 到 100 的整数列表,然后根据这些数字创建另外两个列表,并通过打印这两个列表来完成。 However, I am having trouble with getting the second list to write to a file named target list.txt.
但是,我无法将第二个列表写入名为 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()
target_list
instead of a new file.target_list
的名称而不是新文件。 This is what's causing your program to fail.return
a new list on each call.return
一个新列表。 This prevents the one call of the function from effecting the behavior of the next call.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)
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. target_list.write
是您遇到错误的地方,原因是因为target_list
是一个函数而不是一个文件。
You have multiple problems with scope .您对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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.