gpt4 book ai didi

关于练习题的Python初学者问题

转载 作者:行者123 更新时间:2023-12-04 08:31:32 25 4
gpt4 key购买 nike

我正在学习 python,需要帮助理解我做错了什么。我试图完成的任务是创建一个从 1 到 100 的整数列表,然后根据这些数字创建另外两个列表,并通过打印这两个列表来完成。但是,我无法将第二个列表写入名为 target list.txt 的文件。有人能告诉我我做错了什么吗?

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而不是一个新文件。这就是导致您的程序失败的原因。
  • 不要在函数中使用全局状态。您可以 return每次通话的新列表。这可以防止函数的一次调用影响下一次调用的行为。
  • 使用函数参数允许函数的行为略有不同。这使得该函数更有用并避免了代码重复。
  • 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)

    关于关于练习题的Python初学者问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64996500/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com